clang 22.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"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/StmtObjC.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/ScopeExit.h"
40#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/Dominators.h"
43#include "llvm/IR/FPEnv.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/MDBuilder.h"
48#include "llvm/Support/CRC.h"
49#include "llvm/Support/xxhash.h"
50#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
51#include "llvm/Transforms/Utils/PromoteMemToReg.h"
52#include <optional>
53
54using namespace clang;
55using namespace CodeGen;
56
57namespace llvm {
58extern cl::opt<bool> EnableSingleByteCoverage;
59} // namespace llvm
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 return true;
73
74 // For now, only in optimized builds.
75 return CGOpts.OptimizationLevel != 0;
76}
77
78CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
79 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
80 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
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 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
96 assert(DeferredDeactivationCleanupStack.empty() &&
97 "missed to deactivate a cleanup");
98
99 if (getLangOpts().OpenMP && CurFn)
100 CGM.getOpenMPRuntime().functionFinished(*this);
101
102 // If we have an OpenMPIRBuilder we want to finalize functions (incl.
103 // outlining etc) at some point. Doing it once the function codegen is done
104 // seems to be a reasonable spot. We do it here, as opposed to the deletion
105 // time of the CodeGenModule, because we have to ensure the IR has not yet
106 // been "emitted" to the outside, thus, modifications are still sensible.
107 if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
108 CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
109}
110
111// Map the LangOption for exception behavior into
112// the corresponding enum in the IR.
113llvm::fp::ExceptionBehavior
115
116 switch (Kind) {
117 case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
118 case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
119 case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
120 default:
121 llvm_unreachable("Unsupported FP Exception Behavior");
122 }
123}
124
126 llvm::FastMathFlags FMF;
127 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
128 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
129 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
130 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
131 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
132 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
133 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
134 Builder.setFastMathFlags(FMF);
135}
136
138 const Expr *E)
139 : CGF(CGF) {
140 ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
141}
142
144 FPOptions FPFeatures)
145 : CGF(CGF) {
146 ConstructorHelper(FPFeatures);
147}
148
149void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
150 OldFPFeatures = CGF.CurFPFeatures;
151 CGF.CurFPFeatures = FPFeatures;
152
153 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
154 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
155
156 if (OldFPFeatures == FPFeatures)
157 return;
158
159 FMFGuard.emplace(CGF.Builder);
160
161 llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode();
162 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
163 auto NewExceptionBehavior =
165 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
166
167 CGF.SetFastMathFlags(FPFeatures);
168
169 assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
170 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
171 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
172 (NewExceptionBehavior == llvm::fp::ebIgnore &&
173 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
174 "FPConstrained should be enabled on entire function");
175
176 auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
177 auto OldValue =
178 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
179 auto NewValue = OldValue & Value;
180 if (OldValue != NewValue)
181 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
182 };
183 mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
184 mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
185 mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
186 mergeFnAttrValue(
187 "unsafe-fp-math",
188 FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
189 FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
190 FPFeatures.allowFPContractAcrossStatement());
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 return TEK_Scalar;
289
290 // Complexes.
291 case Type::Complex:
292 return TEK_Complex;
293
294 // Arrays, records, and Objective-C objects.
295 case Type::ConstantArray:
296 case Type::IncompleteArray:
297 case Type::VariableArray:
298 case Type::Record:
299 case Type::ObjCObject:
300 case Type::ObjCInterface:
301 case Type::ArrayParameter:
302 return TEK_Aggregate;
303
304 // We operate on atomic values according to their underlying type.
305 case Type::Atomic:
306 type = cast<AtomicType>(type)->getValueType();
307 continue;
308 }
309 llvm_unreachable("unknown type kind!");
310 }
311}
312
314 // For cleanliness, we try to avoid emitting the return block for
315 // simple cases.
316 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
317
318 if (CurBB) {
319 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
320
321 // We have a valid insert point, reuse it if it is empty or there are no
322 // explicit jumps to the return block.
323 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
324 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
325 delete ReturnBlock.getBlock();
327 } else
328 EmitBlock(ReturnBlock.getBlock());
329 return llvm::DebugLoc();
330 }
331
332 // Otherwise, if the return block is the target of a single direct
333 // branch then we can just put the code in that block instead. This
334 // cleans up functions which started with a unified return block.
335 if (ReturnBlock.getBlock()->hasOneUse()) {
336 llvm::BranchInst *BI =
337 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
338 if (BI && BI->isUnconditional() &&
339 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(*this, 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 }
850 if (SanOpts.has(SanitizerKind::SafeStack))
851 Fn->addFnAttr(llvm::Attribute::SafeStack);
852 if (SanOpts.has(SanitizerKind::ShadowCallStack))
853 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
854
855 if (SanOpts.has(SanitizerKind::Realtime))
856 if (FD && FD->getASTContext().hasAnyFunctionEffects())
857 for (const FunctionEffectWithCondition &Fe : FD->getFunctionEffects()) {
858 if (Fe.Effect.kind() == FunctionEffect::Kind::NonBlocking)
859 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
860 else if (Fe.Effect.kind() == FunctionEffect::Kind::Blocking)
861 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
862 }
863
864 // Apply fuzzing attribute to the function.
865 if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
866 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
867
868 // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
869 // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
870 if (SanOpts.has(SanitizerKind::Thread)) {
871 if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
872 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
873 if (OMD->getMethodFamily() == OMF_dealloc ||
874 OMD->getMethodFamily() == OMF_initialize ||
875 (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
877 }
878 }
879 }
880
881 // Ignore unrelated casts in STL allocate() since the allocator must cast
882 // from void* to T* before object initialization completes. Don't match on the
883 // namespace because not all allocators are in std::
884 if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
886 SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
887 }
888
889 // Ignore null checks in coroutine functions since the coroutines passes
890 // are not aware of how to move the extra UBSan instructions across the split
891 // coroutine boundaries.
892 if (D && SanOpts.has(SanitizerKind::Null))
893 if (FD && FD->getBody() &&
894 FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
895 SanOpts.Mask &= ~SanitizerKind::Null;
896
897 // Apply xray attributes to the function (as a string, for now)
898 bool AlwaysXRayAttr = false;
899 if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
900 if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
902 CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
904 if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
905 Fn->addFnAttr("function-instrument", "xray-always");
906 AlwaysXRayAttr = true;
907 }
908 if (XRayAttr->neverXRayInstrument())
909 Fn->addFnAttr("function-instrument", "xray-never");
910 if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
912 Fn->addFnAttr("xray-log-args",
913 llvm::utostr(LogArgs->getArgumentCount()));
914 }
915 } else {
916 if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
917 Fn->addFnAttr(
918 "xray-instruction-threshold",
919 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
920 }
921
923 if (CGM.getCodeGenOpts().XRayIgnoreLoops)
924 Fn->addFnAttr("xray-ignore-loops");
925
926 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
928 Fn->addFnAttr("xray-skip-exit");
929
930 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
932 Fn->addFnAttr("xray-skip-entry");
933
934 auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
935 if (FuncGroups > 1) {
936 auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(),
937 CurFn->getName().bytes_end());
938 auto Group = crc32(FuncName) % FuncGroups;
939 if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
940 !AlwaysXRayAttr)
941 Fn->addFnAttr("function-instrument", "xray-never");
942 }
943 }
944
945 if (CGM.getCodeGenOpts().getProfileInstr() !=
946 llvm::driver::ProfileInstrKind::ProfileNone) {
947 switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) {
949 Fn->addFnAttr(llvm::Attribute::SkipProfile);
950 break;
952 Fn->addFnAttr(llvm::Attribute::NoProfile);
953 break;
955 break;
956 }
957 }
958
959 unsigned Count, Offset;
960 StringRef Section;
961 if (const auto *Attr =
962 D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
963 Count = Attr->getCount();
964 Offset = Attr->getOffset();
965 Section = Attr->getSection();
966 } else {
967 Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
968 Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
969 }
970 if (Section.empty())
971 Section = CGM.getCodeGenOpts().PatchableFunctionEntrySection;
972 if (Count && Offset <= Count) {
973 Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
974 if (Offset)
975 Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
976 if (!Section.empty())
977 Fn->addFnAttr("patchable-function-entry-section", Section);
978 }
979 // Instruct that functions for COFF/CodeView targets should start with a
980 // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
981 // backends as they don't need it -- instructions on these architectures are
982 // always atomically patchable at runtime.
983 if (CGM.getCodeGenOpts().HotPatch &&
984 getContext().getTargetInfo().getTriple().isX86() &&
985 getContext().getTargetInfo().getTriple().getEnvironment() !=
986 llvm::Triple::CODE16)
987 Fn->addFnAttr("patchable-function", "prologue-short-redirect");
988
989 // Add no-jump-tables value.
990 if (CGM.getCodeGenOpts().NoUseJumpTables)
991 Fn->addFnAttr("no-jump-tables", "true");
992
993 // Add no-inline-line-tables value.
994 if (CGM.getCodeGenOpts().NoInlineLineTables)
995 Fn->addFnAttr("no-inline-line-tables");
996
997 // Add profile-sample-accurate value.
998 if (CGM.getCodeGenOpts().ProfileSampleAccurate)
999 Fn->addFnAttr("profile-sample-accurate");
1000
1001 if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
1002 Fn->addFnAttr("use-sample-profile");
1003
1004 if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
1005 Fn->addFnAttr("cfi-canonical-jump-table");
1006
1007 if (D && D->hasAttr<NoProfileFunctionAttr>())
1008 Fn->addFnAttr(llvm::Attribute::NoProfile);
1009
1010 if (D && D->hasAttr<HybridPatchableAttr>())
1011 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1012
1013 if (D) {
1014 // Function attributes take precedence over command line flags.
1015 if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) {
1016 switch (A->getThunkType()) {
1017 case FunctionReturnThunksAttr::Kind::Keep:
1018 break;
1019 case FunctionReturnThunksAttr::Kind::Extern:
1020 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1021 break;
1022 }
1023 } else if (CGM.getCodeGenOpts().FunctionReturnThunks)
1024 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1025 }
1026
1027 if (FD && (getLangOpts().OpenCL ||
1028 (getLangOpts().CUDA &&
1029 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1030 ((getLangOpts().HIP || getLangOpts().OffloadViaLLVM) &&
1031 getLangOpts().CUDAIsDevice))) {
1032 // Add metadata for a kernel function.
1033 EmitKernelMetadata(FD, Fn);
1034 }
1035
1036 if (FD && FD->hasAttr<ClspvLibclcBuiltinAttr>()) {
1037 Fn->setMetadata("clspv_libclc_builtin",
1038 llvm::MDNode::get(getLLVMContext(), {}));
1039 }
1040
1041 // If we are checking function types, emit a function type signature as
1042 // prologue data.
1043 if (FD && SanOpts.has(SanitizerKind::Function)) {
1044 if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
1045 llvm::LLVMContext &Ctx = Fn->getContext();
1046 llvm::MDBuilder MDB(Ctx);
1047 Fn->setMetadata(
1048 llvm::LLVMContext::MD_func_sanitize,
1049 MDB.createRTTIPointerPrologue(
1050 PrologueSig, getUBSanFunctionTypeHash(FD->getType())));
1051 }
1052 }
1053
1054 // If we're checking nullability, we need to know whether we can check the
1055 // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
1056 if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
1057 auto Nullability = FnRetTy->getNullability();
1058 if (Nullability && *Nullability == NullabilityKind::NonNull &&
1059 !FnRetTy->isRecordType()) {
1060 if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1061 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
1062 RetValNullabilityPrecondition =
1063 llvm::ConstantInt::getTrue(getLLVMContext());
1064 }
1065 }
1066
1067 // If we're in C++ mode and the function name is "main", it is guaranteed
1068 // to be norecurse by the standard (3.6.1.3 "The function main shall not be
1069 // used within a program").
1070 //
1071 // OpenCL C 2.0 v2.2-11 s6.9.i:
1072 // Recursion is not supported.
1073 //
1074 // HLSL
1075 // Recursion is not supported.
1076 //
1077 // SYCL v1.2.1 s3.10:
1078 // kernels cannot include RTTI information, exception classes,
1079 // recursive code, virtual functions or make use of C++ libraries that
1080 // are not compiled for the device.
1081 if (FD &&
1082 ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
1083 getLangOpts().HLSL || getLangOpts().SYCLIsDevice ||
1084 (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
1085 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1086
1087 llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode();
1088 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1089 ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode());
1090 Builder.setDefaultConstrainedRounding(RM);
1091 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1092 if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
1093 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1094 RM != llvm::RoundingMode::NearestTiesToEven))) {
1095 Builder.setIsFPConstrained(true);
1096 Fn->addFnAttr(llvm::Attribute::StrictFP);
1097 }
1098
1099 // If a custom alignment is used, force realigning to this alignment on
1100 // any main function which certainly will need it.
1101 if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
1102 CGM.getCodeGenOpts().StackAlignment))
1103 Fn->addFnAttr("stackrealign");
1104
1105 // "main" doesn't need to zero out call-used registers.
1106 if (FD && FD->isMain())
1107 Fn->removeFnAttr("zero-call-used-regs");
1108
1109 // Add vscale_range attribute if appropriate.
1110 llvm::StringMap<bool> FeatureMap;
1111 auto IsArmStreaming = TargetInfo::ArmStreamingKind::NotStreaming;
1112 if (FD) {
1113 getContext().getFunctionFeatureMap(FeatureMap, FD);
1114 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
1115 if (T->getAArch64SMEAttributes() &
1118
1119 if (IsArmStreamingFunction(FD, true))
1121 }
1122 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
1123 getContext().getTargetInfo().getVScaleRange(getLangOpts(), IsArmStreaming,
1124 &FeatureMap);
1125 if (VScaleRange) {
1126 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
1127 getLLVMContext(), VScaleRange->first, VScaleRange->second));
1128 }
1129
1130 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
1131
1132 // Create a marker to make it easy to insert allocas into the entryblock
1133 // later. Don't create this with the builder, because we don't want it
1134 // folded.
1135 llvm::Value *Poison = llvm::PoisonValue::get(Int32Ty);
1136 AllocaInsertPt = new llvm::BitCastInst(Poison, Int32Ty, "allocapt", EntryBB);
1137
1139
1140 Builder.SetInsertPoint(EntryBB);
1141
1142 // If we're checking the return value, allocate space for a pointer to a
1143 // precise source location of the checked return statement.
1144 if (requiresReturnValueCheck()) {
1145 ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
1146 Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
1147 ReturnLocation);
1148 }
1149
1150 // Emit subprogram debug descriptor.
1151 if (CGDebugInfo *DI = getDebugInfo()) {
1152 // Reconstruct the type from the argument list so that implicit parameters,
1153 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1154 // convention.
1155 DI->emitFunctionStart(GD, Loc, StartLoc,
1156 DI->getFunctionType(FD, RetTy, Args), CurFn,
1158 }
1159
1161 if (CGM.getCodeGenOpts().InstrumentFunctions)
1162 CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1163 if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1164 CurFn->addFnAttr("instrument-function-entry-inlined",
1165 "__cyg_profile_func_enter");
1166 if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1167 CurFn->addFnAttr("instrument-function-entry-inlined",
1168 "__cyg_profile_func_enter_bare");
1169 }
1170
1171 // Since emitting the mcount call here impacts optimizations such as function
1172 // inlining, we just add an attribute to insert a mcount call in backend.
1173 // The attribute "counting-function" is set to mcount function name which is
1174 // architecture dependent.
1175 if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1176 // Calls to fentry/mcount should not be generated if function has
1177 // the no_instrument_function attribute.
1178 if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1179 if (CGM.getCodeGenOpts().CallFEntry)
1180 Fn->addFnAttr("fentry-call", "true");
1181 else {
1182 Fn->addFnAttr("instrument-function-entry-inlined",
1183 getTarget().getMCountName());
1184 }
1185 if (CGM.getCodeGenOpts().MNopMCount) {
1186 if (!CGM.getCodeGenOpts().CallFEntry)
1187 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1188 << "-mnop-mcount" << "-mfentry";
1189 Fn->addFnAttr("mnop-mcount");
1190 }
1191
1192 if (CGM.getCodeGenOpts().RecordMCount) {
1193 if (!CGM.getCodeGenOpts().CallFEntry)
1194 CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1195 << "-mrecord-mcount" << "-mfentry";
1196 Fn->addFnAttr("mrecord-mcount");
1197 }
1198 }
1199 }
1200
1201 if (CGM.getCodeGenOpts().PackedStack) {
1202 if (getContext().getTargetInfo().getTriple().getArch() !=
1203 llvm::Triple::systemz)
1204 CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1205 << "-mpacked-stack";
1206 Fn->addFnAttr("packed-stack");
1207 }
1208
1209 if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1210 !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
1211 Fn->addFnAttr("warn-stack-size",
1212 std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1213
1214 if (RetTy->isVoidType()) {
1215 // Void type; nothing to return.
1217
1218 // Count the implicit return.
1219 if (!endsWithReturn(D))
1220 ++NumReturnExprs;
1221 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1222 // Indirect return; emit returned value directly into sret slot.
1223 // This reduces code size, and affects correctness in C++.
1224 auto AI = CurFn->arg_begin();
1225 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1226 ++AI;
1228 &*AI, RetTy, CurFnInfo->getReturnInfo().getIndirectAlign(), false,
1229 nullptr, nullptr, KnownNonNull);
1230 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1232 CreateDefaultAlignTempAlloca(ReturnValue.getType(), "result.ptr");
1233 Builder.CreateStore(ReturnValue.emitRawPointer(*this),
1235 }
1236 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1237 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1238 // Load the sret pointer from the argument struct and return into that.
1239 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1240 llvm::Function::arg_iterator EI = CurFn->arg_end();
1241 --EI;
1242 llvm::Value *Addr = Builder.CreateStructGEP(
1243 CurFnInfo->getArgStruct(), &*EI, Idx);
1244 llvm::Type *Ty =
1245 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1247 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1249 CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
1250 } else {
1251 ReturnValue = CreateIRTemp(RetTy, "retval");
1252
1253 // Tell the epilog emitter to autorelease the result. We do this
1254 // now so that various specialized functions can suppress it
1255 // during their IR-generation.
1256 if (getLangOpts().ObjCAutoRefCount &&
1257 !CurFnInfo->isReturnsRetained() &&
1258 RetTy->isObjCRetainableType())
1259 AutoreleaseResult = true;
1260 }
1261
1263
1264 PrologueCleanupDepth = EHStack.stable_begin();
1265
1266 // Emit OpenMP specific initialization of the device functions.
1267 if (getLangOpts().OpenMP && CurCodeDecl)
1268 CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1269
1270 if (FD && getLangOpts().HLSL) {
1271 // Handle emitting HLSL entry functions.
1272 if (FD->hasAttr<HLSLShaderAttr>()) {
1273 CGM.getHLSLRuntime().emitEntryFunction(FD, Fn);
1274 }
1275 }
1276
1278
1279 if (const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(D);
1280 MD && !MD->isStatic()) {
1281 bool IsInLambda =
1282 MD->getParent()->isLambda() && MD->getOverloadedOperator() == OO_Call;
1284 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1285 if (IsInLambda) {
1286 // We're in a lambda; figure out the captures.
1290 // If the lambda captures the object referred to by '*this' - either by
1291 // value or by reference, make sure CXXThisValue points to the correct
1292 // object.
1293
1294 // Get the lvalue for the field (which is a copy of the enclosing object
1295 // or contains the address of the enclosing object).
1297 if (!LambdaThisCaptureField->getType()->isPointerType()) {
1298 // If the enclosing object was captured by value, just use its
1299 // address. Sign this pointer.
1300 CXXThisValue = ThisFieldLValue.getPointer(*this);
1301 } else {
1302 // Load the lvalue pointed to by the field, since '*this' was captured
1303 // by reference.
1304 CXXThisValue =
1305 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1306 }
1307 }
1308 for (auto *FD : MD->getParent()->fields()) {
1309 if (FD->hasCapturedVLAType()) {
1310 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1312 auto VAT = FD->getCapturedVLAType();
1313 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1314 }
1315 }
1316 } else if (MD->isImplicitObjectMemberFunction()) {
1317 // Not in a lambda; just use 'this' from the method.
1318 // FIXME: Should we generate a new load for each use of 'this'? The
1319 // fast register allocator would be happier...
1320 CXXThisValue = CXXABIThisValue;
1321 }
1322
1323 // Check the 'this' pointer once per function, if it's available.
1324 if (CXXABIThisValue) {
1325 SanitizerSet SkippedChecks;
1326 SkippedChecks.set(SanitizerKind::ObjectSize, true);
1327 QualType ThisTy = MD->getThisType();
1328
1329 // If this is the call operator of a lambda with no captures, it
1330 // may have a static invoker function, which may call this operator with
1331 // a null 'this' pointer.
1333 SkippedChecks.set(SanitizerKind::Null, true);
1334
1337 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1338 }
1339 }
1340
1341 // If any of the arguments have a variably modified type, make sure to
1342 // emit the type size, but only if the function is not naked. Naked functions
1343 // have no prolog to run this evaluation.
1344 if (!FD || !FD->hasAttr<NakedAttr>()) {
1345 for (const VarDecl *VD : Args) {
1346 // Dig out the type as written from ParmVarDecls; it's unclear whether
1347 // the standard (C99 6.9.1p10) requires this, but we're following the
1348 // precedent set by gcc.
1349 QualType Ty;
1350 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1351 Ty = PVD->getOriginalType();
1352 else
1353 Ty = VD->getType();
1354
1355 if (Ty->isVariablyModifiedType())
1357 }
1358 }
1359 // Emit a location at the end of the prologue.
1360 if (CGDebugInfo *DI = getDebugInfo())
1361 DI->EmitLocation(Builder, StartLoc);
1362 // TODO: Do we need to handle this in two places like we do with
1363 // target-features/target-cpu?
1364 if (CurFuncDecl)
1365 if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1366 LargestVectorWidth = VecWidth->getVectorWidth();
1367
1368 if (CGM.shouldEmitConvergenceTokens())
1369 ConvergenceTokenStack.push_back(getOrEmitConvergenceEntryToken(CurFn));
1370}
1371
1375 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1377 else
1378 EmitStmt(Body);
1379}
1380
1381/// When instrumenting to collect profile data, the counts for some blocks
1382/// such as switch cases need to not include the fall-through counts, so
1383/// emit a branch around the instrumentation code. When not instrumenting,
1384/// this just calls EmitBlock().
1386 const Stmt *S) {
1387 llvm::BasicBlock *SkipCountBB = nullptr;
1388 // Do not skip over the instrumentation when single byte coverage mode is
1389 // enabled.
1390 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1392 // When instrumenting for profiling, the fallthrough to certain
1393 // statements needs to skip over the instrumentation code so that we
1394 // get an accurate count.
1395 SkipCountBB = createBasicBlock("skipcount");
1396 EmitBranch(SkipCountBB);
1397 }
1398 EmitBlock(BB);
1399 uint64_t CurrentCount = getCurrentProfileCount();
1402 if (SkipCountBB)
1403 EmitBlock(SkipCountBB);
1404}
1405
1406/// Tries to mark the given function nounwind based on the
1407/// non-existence of any throwing calls within it. We believe this is
1408/// lightweight enough to do at -O0.
1409static void TryMarkNoThrow(llvm::Function *F) {
1410 // LLVM treats 'nounwind' on a function as part of the type, so we
1411 // can't do this on functions that can be overwritten.
1412 if (F->isInterposable()) return;
1413
1414 for (llvm::BasicBlock &BB : *F)
1415 for (llvm::Instruction &I : BB)
1416 if (I.mayThrow())
1417 return;
1418
1419 F->setDoesNotThrow();
1420}
1421
1423 FunctionArgList &Args) {
1424 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1425 QualType ResTy = FD->getReturnType();
1426
1427 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1428 if (MD && MD->isImplicitObjectMemberFunction()) {
1429 if (CGM.getCXXABI().HasThisReturn(GD))
1430 ResTy = MD->getThisType();
1431 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1432 ResTy = CGM.getContext().VoidPtrTy;
1433 CGM.getCXXABI().buildThisParam(*this, Args);
1434 }
1435
1436 // The base version of an inheriting constructor whose constructed base is a
1437 // virtual base is not passed any arguments (because it doesn't actually call
1438 // the inherited constructor).
1439 bool PassedParams = true;
1440 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1441 if (auto Inherited = CD->getInheritedConstructor())
1442 PassedParams =
1443 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1444
1445 if (PassedParams) {
1446 for (auto *Param : FD->parameters()) {
1447 Args.push_back(Param);
1448 if (!Param->hasAttr<PassObjectSizeAttr>())
1449 continue;
1450
1452 getContext(), Param->getDeclContext(), Param->getLocation(),
1453 /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamKind::Other);
1454 SizeArguments[Param] = Implicit;
1455 Args.push_back(Implicit);
1456 }
1457 }
1458
1459 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1460 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1461
1462 return ResTy;
1463}
1464
1465void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1466 const CGFunctionInfo &FnInfo) {
1467 assert(Fn && "generating code for null Function");
1468 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1469 CurGD = GD;
1470
1471 FunctionArgList Args;
1472 QualType ResTy = BuildFunctionArgList(GD, Args);
1473
1474 CGM.getTargetCodeGenInfo().checkFunctionABI(CGM, FD);
1475
1476 if (FD->isInlineBuiltinDeclaration()) {
1477 // When generating code for a builtin with an inline declaration, use a
1478 // mangled name to hold the actual body, while keeping an external
1479 // definition in case the function pointer is referenced somewhere.
1480 std::string FDInlineName = (Fn->getName() + ".inline").str();
1481 llvm::Module *M = Fn->getParent();
1482 llvm::Function *Clone = M->getFunction(FDInlineName);
1483 if (!Clone) {
1484 Clone = llvm::Function::Create(Fn->getFunctionType(),
1485 llvm::GlobalValue::InternalLinkage,
1486 Fn->getAddressSpace(), FDInlineName, M);
1487 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1488 }
1489 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1490 Fn = Clone;
1491 } else {
1492 // Detect the unusual situation where an inline version is shadowed by a
1493 // non-inline version. In that case we should pick the external one
1494 // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1495 // to detect that situation before we reach codegen, so do some late
1496 // replacement.
1497 for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1498 PD = PD->getPreviousDecl()) {
1499 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1500 std::string FDInlineName = (Fn->getName() + ".inline").str();
1501 llvm::Module *M = Fn->getParent();
1502 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1503 Clone->replaceAllUsesWith(Fn);
1504 Clone->eraseFromParent();
1505 }
1506 break;
1507 }
1508 }
1509 }
1510
1511 // Check if we should generate debug info for this function.
1512 if (FD->hasAttr<NoDebugAttr>()) {
1513 // Clear non-distinct debug info that was possibly attached to the function
1514 // due to an earlier declaration without the nodebug attribute
1515 Fn->setSubprogram(nullptr);
1516 // Disable debug info indefinitely for this function
1517 DebugInfo = nullptr;
1518 }
1519 // Finalize function debug info on exit.
1520 auto Cleanup = llvm::make_scope_exit([this] {
1521 if (CGDebugInfo *DI = getDebugInfo())
1522 DI->completeFunction();
1523 });
1524
1525 // The function might not have a body if we're generating thunks for a
1526 // function declaration.
1527 SourceRange BodyRange;
1528 if (Stmt *Body = FD->getBody())
1529 BodyRange = Body->getSourceRange();
1530 else
1531 BodyRange = FD->getLocation();
1532 CurEHLocation = BodyRange.getEnd();
1533
1534 // Use the location of the start of the function to determine where
1535 // the function definition is located. By default use the location
1536 // of the declaration as the location for the subprogram. A function
1537 // may lack a declaration in the source code if it is created by code
1538 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1539 SourceLocation Loc = FD->getLocation();
1540
1541 // If this is a function specialization then use the pattern body
1542 // as the location for the function.
1543 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1544 if (SpecDecl->hasBody(SpecDecl))
1545 Loc = SpecDecl->getLocation();
1546
1547 Stmt *Body = FD->getBody();
1548
1549 if (Body) {
1550 // Coroutines always emit lifetime markers.
1551 if (isa<CoroutineBodyStmt>(Body))
1552 ShouldEmitLifetimeMarkers = true;
1553
1554 // Initialize helper which will detect jumps which can cause invalid
1555 // lifetime markers.
1556 if (ShouldEmitLifetimeMarkers)
1557 Bypasses.Init(CGM, Body);
1558 }
1559
1560 // Emit the standard function prologue.
1561 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1562
1563 // Save parameters for coroutine function.
1564 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1565 llvm::append_range(FnArgs, FD->parameters());
1566
1567 // Ensure that the function adheres to the forward progress guarantee, which
1568 // is required by certain optimizations.
1569 // In C++11 and up, the attribute will be removed if the body contains a
1570 // trivial empty loop.
1572 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1573
1574 // Generate the body of the function.
1575 PGO->assignRegionCounters(GD, CurFn);
1576 if (isa<CXXDestructorDecl>(FD))
1577 EmitDestructorBody(Args);
1578 else if (isa<CXXConstructorDecl>(FD))
1579 EmitConstructorBody(Args);
1580 else if (getLangOpts().CUDA &&
1581 !getLangOpts().CUDAIsDevice &&
1582 FD->hasAttr<CUDAGlobalAttr>())
1583 CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1584 else if (isa<CXXMethodDecl>(FD) &&
1585 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1586 // The lambda static invoker function is special, because it forwards or
1587 // clones the body of the function call operator (but is actually static).
1589 } else if (isa<CXXMethodDecl>(FD) &&
1591 !FnInfo.isDelegateCall() &&
1592 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1593 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1594 // If emitting a lambda with static invoker on X86 Windows, change
1595 // the call operator body.
1596 // Make sure that this is a call operator with an inalloca arg and check
1597 // for delegate call to make sure this is the original call op and not the
1598 // new forwarding function for the static invoker.
1600 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1601 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1602 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1603 // Implicit copy-assignment gets the same special treatment as implicit
1604 // copy-constructors.
1606 } else if (DeviceKernelAttr::isOpenCLSpelling(
1607 FD->getAttr<DeviceKernelAttr>()) &&
1609 CallArgList CallArgs;
1610 for (unsigned i = 0; i < Args.size(); ++i) {
1611 Address ArgAddr = GetAddrOfLocalVar(Args[i]);
1612 QualType ArgQualType = Args[i]->getType();
1613 RValue ArgRValue = convertTempToRValue(ArgAddr, ArgQualType, Loc);
1614 CallArgs.add(ArgRValue, ArgQualType);
1615 }
1617 const FunctionType *FT = cast<FunctionType>(FD->getType());
1618 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
1619 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
1620 CallArgs, FT, /*ChainCall=*/false);
1621 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FnInfo);
1622 llvm::Constant *GDStubFunctionPointer =
1623 CGM.getRawFunctionPointer(GDStub, FTy);
1624 CGCallee GDStubCallee = CGCallee::forDirect(GDStubFunctionPointer, GDStub);
1625 EmitCall(FnInfo, GDStubCallee, ReturnValueSlot(), CallArgs, nullptr, false,
1626 Loc);
1627 } else if (Body) {
1628 EmitFunctionBody(Body);
1629 } else
1630 llvm_unreachable("no definition for emitted function");
1631
1632 // C++11 [stmt.return]p2:
1633 // Flowing off the end of a function [...] results in undefined behavior in
1634 // a value-returning function.
1635 // C11 6.9.1p12:
1636 // If the '}' that terminates a function is reached, and the value of the
1637 // function call is used by the caller, the behavior is undefined.
1639 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1640 bool ShouldEmitUnreachable =
1641 CGM.getCodeGenOpts().StrictReturn ||
1642 !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1643 if (SanOpts.has(SanitizerKind::Return)) {
1644 auto CheckOrdinal = SanitizerKind::SO_Return;
1645 auto CheckHandler = SanitizerHandler::MissingReturn;
1646 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
1647 llvm::Value *IsFalse = Builder.getFalse();
1648 EmitCheck(std::make_pair(IsFalse, CheckOrdinal), CheckHandler,
1650 } else if (ShouldEmitUnreachable) {
1651 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1652 EmitTrapCall(llvm::Intrinsic::trap);
1653 }
1654 if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1655 Builder.CreateUnreachable();
1656 Builder.ClearInsertionPoint();
1657 }
1658 }
1659
1660 // Emit the standard function epilogue.
1661 FinishFunction(BodyRange.getEnd());
1662
1663 PGO->verifyCounterMap();
1664
1665 // If we haven't marked the function nothrow through other means, do
1666 // a quick pass now to see if we can.
1667 if (!CurFn->doesNotThrow())
1669}
1670
1671/// ContainsLabel - Return true if the statement contains a label in it. If
1672/// this statement is not executed normally, it not containing a label means
1673/// that we can just remove the code.
1674bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1675 // Null statement, not a label!
1676 if (!S) return false;
1677
1678 // If this is a label, we have to emit the code, consider something like:
1679 // if (0) { ... foo: bar(); } goto foo;
1680 //
1681 // TODO: If anyone cared, we could track __label__'s, since we know that you
1682 // can't jump to one from outside their declared region.
1683 if (isa<LabelStmt>(S))
1684 return true;
1685
1686 // If this is a case/default statement, and we haven't seen a switch, we have
1687 // to emit the code.
1688 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1689 return true;
1690
1691 // If this is a switch statement, we want to ignore cases below it.
1692 if (isa<SwitchStmt>(S))
1693 IgnoreCaseStmts = true;
1694
1695 // Scan subexpressions for verboten labels.
1696 for (const Stmt *SubStmt : S->children())
1697 if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1698 return true;
1699
1700 return false;
1701}
1702
1703/// containsBreak - Return true if the statement contains a break out of it.
1704/// If the statement (recursively) contains a switch or loop with a break
1705/// inside of it, this is fine.
1707 // Null statement, not a label!
1708 if (!S) return false;
1709
1710 // If this is a switch or loop that defines its own break scope, then we can
1711 // include it and anything inside of it.
1712 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1713 isa<ForStmt>(S))
1714 return false;
1715
1716 if (isa<BreakStmt>(S))
1717 return true;
1718
1719 // Scan subexpressions for verboten breaks.
1720 for (const Stmt *SubStmt : S->children())
1721 if (containsBreak(SubStmt))
1722 return true;
1723
1724 return false;
1725}
1726
1728 if (!S) return false;
1729
1730 // Some statement kinds add a scope and thus never add a decl to the current
1731 // scope. Note, this list is longer than the list of statements that might
1732 // have an unscoped decl nested within them, but this way is conservatively
1733 // correct even if more statement kinds are added.
1734 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1738 return false;
1739
1740 if (isa<DeclStmt>(S))
1741 return true;
1742
1743 for (const Stmt *SubStmt : S->children())
1744 if (mightAddDeclToScope(SubStmt))
1745 return true;
1746
1747 return false;
1748}
1749
1750/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1751/// to a constant, or if it does but contains a label, return false. If it
1752/// constant folds return true and set the boolean result in Result.
1754 bool &ResultBool,
1755 bool AllowLabels) {
1756 // If MC/DC is enabled, disable folding so that we can instrument all
1757 // conditions to yield complete test vectors. We still keep track of
1758 // folded conditions during region mapping and visualization.
1759 if (!AllowLabels && CGM.getCodeGenOpts().hasProfileClangInstr() &&
1760 CGM.getCodeGenOpts().MCDCCoverage)
1761 return false;
1762
1763 llvm::APSInt ResultInt;
1764 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1765 return false;
1766
1767 ResultBool = ResultInt.getBoolValue();
1768 return true;
1769}
1770
1771/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1772/// to a constant, or if it does but contains a label, return false. If it
1773/// constant folds return true and set the folded value.
1775 llvm::APSInt &ResultInt,
1776 bool AllowLabels) {
1777 // FIXME: Rename and handle conversion of other evaluatable things
1778 // to bool.
1780 if (!Cond->EvaluateAsInt(Result, getContext()))
1781 return false; // Not foldable, not integer or not fully evaluatable.
1782
1783 llvm::APSInt Int = Result.Val.getInt();
1784 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1785 return false; // Contains a label.
1786
1787 PGO->markStmtMaybeUsed(Cond);
1788 ResultInt = Int;
1789 return true;
1790}
1791
1792/// Strip parentheses and simplistic logical-NOT operators.
1794 while (const UnaryOperator *Op = dyn_cast<UnaryOperator>(C->IgnoreParens())) {
1795 if (Op->getOpcode() != UO_LNot)
1796 break;
1797 C = Op->getSubExpr();
1798 }
1799 return C->IgnoreParens();
1800}
1801
1802/// Determine whether the given condition is an instrumentable condition
1803/// (i.e. no "&&" or "||").
1805 const BinaryOperator *BOp = dyn_cast<BinaryOperator>(stripCond(C));
1806 return (!BOp || !BOp->isLogicalOp());
1807}
1808
1809/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1810/// increments a profile counter based on the semantics of the given logical
1811/// operator opcode. This is used to instrument branch condition coverage for
1812/// logical operators.
1814 const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1815 llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1816 Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1817 // If not instrumenting, just emit a branch.
1818 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1819 if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1820 return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1821
1822 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1823
1824 llvm::BasicBlock *ThenBlock = nullptr;
1825 llvm::BasicBlock *ElseBlock = nullptr;
1826 llvm::BasicBlock *NextBlock = nullptr;
1827
1828 // Create the block we'll use to increment the appropriate counter.
1829 llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1830
1831 // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1832 // means we need to evaluate the condition and increment the counter on TRUE:
1833 //
1834 // if (Cond)
1835 // goto CounterIncrBlock;
1836 // else
1837 // goto FalseBlock;
1838 //
1839 // CounterIncrBlock:
1840 // Counter++;
1841 // goto TrueBlock;
1842
1843 if (LOp == BO_LAnd) {
1844 ThenBlock = CounterIncrBlock;
1845 ElseBlock = FalseBlock;
1846 NextBlock = TrueBlock;
1847 }
1848
1849 // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1850 // we need to evaluate the condition and increment the counter on FALSE:
1851 //
1852 // if (Cond)
1853 // goto TrueBlock;
1854 // else
1855 // goto CounterIncrBlock;
1856 //
1857 // CounterIncrBlock:
1858 // Counter++;
1859 // goto FalseBlock;
1860
1861 else if (LOp == BO_LOr) {
1862 ThenBlock = TrueBlock;
1863 ElseBlock = CounterIncrBlock;
1864 NextBlock = FalseBlock;
1865 } else {
1866 llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1867 }
1868
1869 // Emit Branch based on condition.
1870 EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1871
1872 // Emit the block containing the counter increment(s).
1873 EmitBlock(CounterIncrBlock);
1874
1875 // Increment corresponding counter; if index not provided, use Cond as index.
1876 incrementProfileCounter(CntrStmt);
1877
1878 // Go to the next block.
1879 EmitBranch(NextBlock);
1880}
1881
1882/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1883/// statement) to the specified blocks. Based on the condition, this might try
1884/// to simplify the codegen of the conditional based on the branch.
1885/// \param LH The value of the likelihood attribute on the True branch.
1886/// \param ConditionalOp Used by MC/DC code coverage to track the result of the
1887/// ConditionalOperator (ternary) through a recursive call for the operator's
1888/// LHS and RHS nodes.
1890 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1891 uint64_t TrueCount, Stmt::Likelihood LH, const Expr *ConditionalOp,
1892 const VarDecl *ConditionalDecl) {
1893 Cond = Cond->IgnoreParens();
1894
1895 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1896 // Handle X && Y in a condition.
1897 if (CondBOp->getOpcode() == BO_LAnd) {
1898 MCDCLogOpStack.push_back(CondBOp);
1899
1900 // If we have "1 && X", simplify the code. "0 && X" would have constant
1901 // folded if the case was simple enough.
1902 bool ConstantBool = false;
1903 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1904 ConstantBool) {
1905 // br(1 && X) -> br(X).
1906 incrementProfileCounter(CondBOp);
1907 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1908 FalseBlock, TrueCount, LH);
1909 MCDCLogOpStack.pop_back();
1910 return;
1911 }
1912
1913 // If we have "X && 1", simplify the code to use an uncond branch.
1914 // "X && 0" would have been constant folded to 0.
1915 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1916 ConstantBool) {
1917 // br(X && 1) -> br(X).
1918 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1919 FalseBlock, TrueCount, LH, CondBOp);
1920 MCDCLogOpStack.pop_back();
1921 return;
1922 }
1923
1924 // Emit the LHS as a conditional. If the LHS conditional is false, we
1925 // want to jump to the FalseBlock.
1926 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1927 // The counter tells us how often we evaluate RHS, and all of TrueCount
1928 // can be propagated to that branch.
1929 uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1930
1931 ConditionalEvaluation eval(*this);
1932 {
1933 ApplyDebugLocation DL(*this, Cond);
1934 // Propagate the likelihood attribute like __builtin_expect
1935 // __builtin_expect(X && Y, 1) -> X and Y are likely
1936 // __builtin_expect(X && Y, 0) -> only Y is unlikely
1937 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1938 LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1939 EmitBlock(LHSTrue);
1940 }
1941
1942 incrementProfileCounter(CondBOp);
1943 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1944
1945 // Any temporaries created here are conditional.
1946 eval.begin(*this);
1947 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1948 FalseBlock, TrueCount, LH);
1949 eval.end(*this);
1950 MCDCLogOpStack.pop_back();
1951 return;
1952 }
1953
1954 if (CondBOp->getOpcode() == BO_LOr) {
1955 MCDCLogOpStack.push_back(CondBOp);
1956
1957 // If we have "0 || X", simplify the code. "1 || X" would have constant
1958 // folded if the case was simple enough.
1959 bool ConstantBool = false;
1960 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1961 !ConstantBool) {
1962 // br(0 || X) -> br(X).
1963 incrementProfileCounter(CondBOp);
1964 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1965 FalseBlock, TrueCount, LH);
1966 MCDCLogOpStack.pop_back();
1967 return;
1968 }
1969
1970 // If we have "X || 0", simplify the code to use an uncond branch.
1971 // "X || 1" would have been constant folded to 1.
1972 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1973 !ConstantBool) {
1974 // br(X || 0) -> br(X).
1975 EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1976 FalseBlock, TrueCount, LH, CondBOp);
1977 MCDCLogOpStack.pop_back();
1978 return;
1979 }
1980 // Emit the LHS as a conditional. If the LHS conditional is true, we
1981 // want to jump to the TrueBlock.
1982 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1983 // We have the count for entry to the RHS and for the whole expression
1984 // being true, so we can divy up True count between the short circuit and
1985 // the RHS.
1986 uint64_t LHSCount =
1987 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1988 uint64_t RHSCount = TrueCount - LHSCount;
1989
1990 ConditionalEvaluation eval(*this);
1991 {
1992 // Propagate the likelihood attribute like __builtin_expect
1993 // __builtin_expect(X || Y, 1) -> only Y is likely
1994 // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1995 ApplyDebugLocation DL(*this, Cond);
1996 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1997 LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1998 EmitBlock(LHSFalse);
1999 }
2000
2001 incrementProfileCounter(CondBOp);
2002 setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
2003
2004 // Any temporaries created here are conditional.
2005 eval.begin(*this);
2006 EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
2007 RHSCount, LH);
2008
2009 eval.end(*this);
2010 MCDCLogOpStack.pop_back();
2011 return;
2012 }
2013 }
2014
2015 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
2016 // br(!x, t, f) -> br(x, f, t)
2017 // Avoid doing this optimization when instrumenting a condition for MC/DC.
2018 // LNot is taken as part of the condition for simplicity, and changing its
2019 // sense negatively impacts test vector tracking.
2020 bool MCDCCondition = CGM.getCodeGenOpts().hasProfileClangInstr() &&
2021 CGM.getCodeGenOpts().MCDCCoverage &&
2023 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
2024 // Negate the count.
2025 uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
2026 // The values of the enum are chosen to make this negation possible.
2027 LH = static_cast<Stmt::Likelihood>(-LH);
2028 // Negate the condition and swap the destination blocks.
2029 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
2030 FalseCount, LH);
2031 }
2032 }
2033
2034 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
2035 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
2036 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
2037 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
2038
2039 // The ConditionalOperator itself has no likelihood information for its
2040 // true and false branches. This matches the behavior of __builtin_expect.
2041 ConditionalEvaluation cond(*this);
2042 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
2044
2045 // When computing PGO branch weights, we only know the overall count for
2046 // the true block. This code is essentially doing tail duplication of the
2047 // naive code-gen, introducing new edges for which counts are not
2048 // available. Divide the counts proportionally between the LHS and RHS of
2049 // the conditional operator.
2050 uint64_t LHSScaledTrueCount = 0;
2051 if (TrueCount) {
2052 double LHSRatio =
2053 getProfileCount(CondOp) / (double)getCurrentProfileCount();
2054 LHSScaledTrueCount = TrueCount * LHSRatio;
2055 }
2056
2057 cond.begin(*this);
2058 EmitBlock(LHSBlock);
2060 {
2061 ApplyDebugLocation DL(*this, Cond);
2062 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
2063 LHSScaledTrueCount, LH, CondOp);
2064 }
2065 cond.end(*this);
2066
2067 cond.begin(*this);
2068 EmitBlock(RHSBlock);
2069 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
2070 TrueCount - LHSScaledTrueCount, LH, CondOp);
2071 cond.end(*this);
2072
2073 return;
2074 }
2075
2076 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2077 // Conditional operator handling can give us a throw expression as a
2078 // condition for a case like:
2079 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
2080 // Fold this to:
2081 // br(c, throw x, br(y, t, f))
2082 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
2083 return;
2084 }
2085
2086 // Emit the code with the fully general case.
2087 llvm::Value *CondV;
2088 {
2089 ApplyDebugLocation DL(*this, Cond);
2090 CondV = EvaluateExprAsBool(Cond);
2091 }
2092
2093 MaybeEmitDeferredVarDeclInit(ConditionalDecl);
2094
2095 // If not at the top of the logical operator nest, update MCDC temp with the
2096 // boolean result of the evaluated condition.
2097 if (!MCDCLogOpStack.empty()) {
2098 const Expr *MCDCBaseExpr = Cond;
2099 // When a nested ConditionalOperator (ternary) is encountered in a boolean
2100 // expression, MC/DC tracks the result of the ternary, and this is tied to
2101 // the ConditionalOperator expression and not the ternary's LHS or RHS. If
2102 // this is the case, the ConditionalOperator expression is passed through
2103 // the ConditionalOp parameter and then used as the MCDC base expression.
2104 if (ConditionalOp)
2105 MCDCBaseExpr = ConditionalOp;
2106
2107 maybeUpdateMCDCCondBitmap(MCDCBaseExpr, CondV);
2108 }
2109
2110 llvm::MDNode *Weights = nullptr;
2111 llvm::MDNode *Unpredictable = nullptr;
2112
2113 // If the branch has a condition wrapped by __builtin_unpredictable,
2114 // create metadata that specifies that the branch is unpredictable.
2115 // Don't bother if not optimizing because that metadata would not be used.
2116 auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
2117 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
2118 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
2119 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2120 llvm::MDBuilder MDHelper(getLLVMContext());
2121 Unpredictable = MDHelper.createUnpredictable();
2122 }
2123 }
2124
2125 // If there is a Likelihood knowledge for the cond, lower it.
2126 // Note that if not optimizing this won't emit anything.
2127 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2128 if (CondV != NewCondV)
2129 CondV = NewCondV;
2130 else {
2131 // Otherwise, lower profile counts. Note that we do this even at -O0.
2132 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
2133 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2134 }
2135
2136 llvm::Instruction *BrInst = Builder.CreateCondBr(CondV, TrueBlock, FalseBlock,
2137 Weights, Unpredictable);
2138 addInstToNewSourceAtom(BrInst, CondV);
2139
2140 switch (HLSLControlFlowAttr) {
2141 case HLSLControlFlowHintAttr::Microsoft_branch:
2142 case HLSLControlFlowHintAttr::Microsoft_flatten: {
2143 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2144
2145 llvm::ConstantInt *BranchHintConstant =
2147 HLSLControlFlowHintAttr::Spelling::Microsoft_branch
2148 ? llvm::ConstantInt::get(CGM.Int32Ty, 1)
2149 : llvm::ConstantInt::get(CGM.Int32Ty, 2);
2150
2152 {MDHelper.createString("hlsl.controlflow.hint"),
2153 MDHelper.createConstant(BranchHintConstant)});
2154 BrInst->setMetadata("hlsl.controlflow.hint",
2155 llvm::MDNode::get(CGM.getLLVMContext(), Vals));
2156 break;
2157 }
2158 // This is required to avoid warnings during compilation
2159 case HLSLControlFlowHintAttr::SpellingNotCalculated:
2160 break;
2161 }
2162}
2163
2164/// ErrorUnsupported - Print out an error that codegen doesn't support the
2165/// specified stmt yet.
2166void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
2167 CGM.ErrorUnsupported(S, Type);
2168}
2169
2170/// emitNonZeroVLAInit - Emit the "zero" initialization of a
2171/// variable-length array whose elements have a non-zero bit-pattern.
2172///
2173/// \param baseType the inner-most element type of the array
2174/// \param src - a char* pointing to the bit-pattern for a single
2175/// base element of the array
2176/// \param sizeInChars - the total size of the VLA, in chars
2178 Address dest, Address src,
2179 llvm::Value *sizeInChars) {
2180 CGBuilderTy &Builder = CGF.Builder;
2181
2182 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
2183 llvm::Value *baseSizeInChars
2184 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
2185
2186 Address begin = dest.withElementType(CGF.Int8Ty);
2187 llvm::Value *end = Builder.CreateInBoundsGEP(begin.getElementType(),
2188 begin.emitRawPointer(CGF),
2189 sizeInChars, "vla.end");
2190
2191 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
2192 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
2193 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
2194
2195 // Make a loop over the VLA. C99 guarantees that the VLA element
2196 // count must be nonzero.
2197 CGF.EmitBlock(loopBB);
2198
2199 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
2200 cur->addIncoming(begin.emitRawPointer(CGF), originBB);
2201
2202 CharUnits curAlign =
2203 dest.getAlignment().alignmentOfArrayElement(baseSize);
2204
2205 // memcpy the individual element bit-pattern.
2206 Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars,
2207 /*volatile*/ false);
2208
2209 // Go to the next element.
2210 llvm::Value *next =
2211 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
2212
2213 // Leave if that's the end of the VLA.
2214 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
2215 Builder.CreateCondBr(done, contBB, loopBB);
2216 cur->addIncoming(next, loopBB);
2217
2218 CGF.EmitBlock(contBB);
2219}
2220
2221void
2223 // Ignore empty classes in C++.
2224 if (getLangOpts().CPlusPlus)
2225 if (const auto *RD = Ty->getAsCXXRecordDecl(); RD && RD->isEmpty())
2226 return;
2227
2228 if (DestPtr.getElementType() != Int8Ty)
2229 DestPtr = DestPtr.withElementType(Int8Ty);
2230
2231 // Get size and alignment info for this aggregate.
2233
2234 llvm::Value *SizeVal;
2235 const VariableArrayType *vla;
2236
2237 // Don't bother emitting a zero-byte memset.
2238 if (size.isZero()) {
2239 // But note that getTypeInfo returns 0 for a VLA.
2240 if (const VariableArrayType *vlaType =
2241 dyn_cast_or_null<VariableArrayType>(
2242 getContext().getAsArrayType(Ty))) {
2243 auto VlaSize = getVLASize(vlaType);
2244 SizeVal = VlaSize.NumElts;
2245 CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
2246 if (!eltSize.isOne())
2247 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
2248 vla = vlaType;
2249 } else {
2250 return;
2251 }
2252 } else {
2253 SizeVal = CGM.getSize(size);
2254 vla = nullptr;
2255 }
2256
2257 // If the type contains a pointer to data member we can't memset it to zero.
2258 // Instead, create a null constant and copy it to the destination.
2259 // TODO: there are other patterns besides zero that we can usefully memset,
2260 // like -1, which happens to be the pattern used by member-pointers.
2261 if (!CGM.getTypes().isZeroInitializable(Ty)) {
2262 // For a VLA, emit a single element, then splat that over the VLA.
2263 if (vla) Ty = getContext().getBaseElementType(vla);
2264
2265 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
2266
2267 llvm::GlobalVariable *NullVariable =
2268 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
2269 /*isConstant=*/true,
2270 llvm::GlobalVariable::PrivateLinkage,
2271 NullConstant, Twine());
2272 CharUnits NullAlign = DestPtr.getAlignment();
2273 NullVariable->setAlignment(NullAlign.getAsAlign());
2274 Address SrcPtr(NullVariable, Builder.getInt8Ty(), NullAlign);
2275
2276 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
2277
2278 // Get and call the appropriate llvm.memcpy overload.
2279 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2280 return;
2281 }
2282
2283 // Otherwise, just memset the whole thing to zero. This is legal
2284 // because in LLVM, all default initializers (other than the ones we just
2285 // handled above) are guaranteed to have a bit pattern of all zeros.
2286 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2287}
2288
2289llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2290 // Make sure that there is a block for the indirect goto.
2291 if (!IndirectBranch)
2293
2294 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2295
2296 // Make sure the indirect branch includes all of the address-taken blocks.
2297 IndirectBranch->addDestination(BB);
2298 return llvm::BlockAddress::get(CurFn->getType(), BB);
2299}
2300
2302 // If we already made the indirect branch for indirect goto, return its block.
2303 if (IndirectBranch) return IndirectBranch->getParent();
2304
2305 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2306
2307 // Create the PHI node that indirect gotos will add entries to.
2308 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2309 "indirect.goto.dest");
2310
2311 // Create the indirect branch instruction.
2312 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2313 return IndirectBranch->getParent();
2314}
2315
2316/// Computes the length of an array in elements, as well as the base
2317/// element type and a properly-typed first element pointer.
2318llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2319 QualType &baseType,
2320 Address &addr) {
2321 const ArrayType *arrayType = origArrayType;
2322
2323 // If it's a VLA, we have to load the stored size. Note that
2324 // this is the size of the VLA in bytes, not its size in elements.
2325 llvm::Value *numVLAElements = nullptr;
2328
2329 // Walk into all VLAs. This doesn't require changes to addr,
2330 // which has type T* where T is the first non-VLA element type.
2331 do {
2332 QualType elementType = arrayType->getElementType();
2333 arrayType = getContext().getAsArrayType(elementType);
2334
2335 // If we only have VLA components, 'addr' requires no adjustment.
2336 if (!arrayType) {
2337 baseType = elementType;
2338 return numVLAElements;
2339 }
2341
2342 // We get out here only if we find a constant array type
2343 // inside the VLA.
2344 }
2345
2346 // We have some number of constant-length arrays, so addr should
2347 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
2348 // down to the first element of addr.
2350
2351 // GEP down to the array type.
2352 llvm::ConstantInt *zero = Builder.getInt32(0);
2353 gepIndices.push_back(zero);
2354
2355 uint64_t countFromCLAs = 1;
2356 QualType eltType;
2357
2358 llvm::ArrayType *llvmArrayType =
2359 dyn_cast<llvm::ArrayType>(addr.getElementType());
2360 while (llvmArrayType) {
2362 assert(cast<ConstantArrayType>(arrayType)->getZExtSize() ==
2363 llvmArrayType->getNumElements());
2364
2365 gepIndices.push_back(zero);
2366 countFromCLAs *= llvmArrayType->getNumElements();
2367 eltType = arrayType->getElementType();
2368
2369 llvmArrayType =
2370 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2371 arrayType = getContext().getAsArrayType(arrayType->getElementType());
2372 assert((!llvmArrayType || arrayType) &&
2373 "LLVM and Clang types are out-of-synch");
2374 }
2375
2376 if (arrayType) {
2377 // From this point onwards, the Clang array type has been emitted
2378 // as some other type (probably a packed struct). Compute the array
2379 // size, and just emit the 'begin' expression as a bitcast.
2380 while (arrayType) {
2381 countFromCLAs *= cast<ConstantArrayType>(arrayType)->getZExtSize();
2382 eltType = arrayType->getElementType();
2383 arrayType = getContext().getAsArrayType(eltType);
2384 }
2385
2386 llvm::Type *baseType = ConvertType(eltType);
2387 addr = addr.withElementType(baseType);
2388 } else {
2389 // Create the actual GEP.
2390 addr = Address(Builder.CreateInBoundsGEP(addr.getElementType(),
2391 addr.emitRawPointer(*this),
2392 gepIndices, "array.begin"),
2393 ConvertTypeForMem(eltType), addr.getAlignment());
2394 }
2395
2396 baseType = eltType;
2397
2398 llvm::Value *numElements
2399 = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2400
2401 // If we had any VLA dimensions, factor them in.
2402 if (numVLAElements)
2403 numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2404
2405 return numElements;
2406}
2407
2410 assert(vla && "type was not a variable array type!");
2411 return getVLASize(vla);
2412}
2413
2416 // The number of elements so far; always size_t.
2417 llvm::Value *numElements = nullptr;
2418
2419 QualType elementType;
2420 do {
2421 elementType = type->getElementType();
2422 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2423 assert(vlaSize && "no size for VLA!");
2424 assert(vlaSize->getType() == SizeTy);
2425
2426 if (!numElements) {
2427 numElements = vlaSize;
2428 } else {
2429 // It's undefined behavior if this wraps around, so mark it that way.
2430 // FIXME: Teach -fsanitize=undefined to trap this.
2431 numElements = Builder.CreateNUWMul(numElements, vlaSize);
2432 }
2433 } while ((type = getContext().getAsVariableArrayType(elementType)));
2434
2435 return { numElements, elementType };
2436}
2437
2441 assert(vla && "type was not a variable array type!");
2442 return getVLAElements1D(vla);
2443}
2444
2447 llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2448 assert(VlaSize && "no size for VLA!");
2449 assert(VlaSize->getType() == SizeTy);
2450 return { VlaSize, Vla->getElementType() };
2451}
2452
2454 assert(type->isVariablyModifiedType() &&
2455 "Must pass variably modified type to EmitVLASizes!");
2456
2458
2459 // We're going to walk down into the type and look for VLA
2460 // expressions.
2461 do {
2462 assert(type->isVariablyModifiedType());
2463
2464 const Type *ty = type.getTypePtr();
2465 switch (ty->getTypeClass()) {
2466
2467#define TYPE(Class, Base)
2468#define ABSTRACT_TYPE(Class, Base)
2469#define NON_CANONICAL_TYPE(Class, Base)
2470#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2471#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2472#include "clang/AST/TypeNodes.inc"
2473 llvm_unreachable("unexpected dependent type!");
2474
2475 // These types are never variably-modified.
2476 case Type::Builtin:
2477 case Type::Complex:
2478 case Type::Vector:
2479 case Type::ExtVector:
2480 case Type::ConstantMatrix:
2481 case Type::Record:
2482 case Type::Enum:
2483 case Type::Using:
2484 case Type::TemplateSpecialization:
2485 case Type::ObjCTypeParam:
2486 case Type::ObjCObject:
2487 case Type::ObjCInterface:
2488 case Type::ObjCObjectPointer:
2489 case Type::BitInt:
2490 case Type::HLSLInlineSpirv:
2491 case Type::PredefinedSugar:
2492 llvm_unreachable("type class is never variably-modified!");
2493
2494 case Type::Adjusted:
2495 type = cast<AdjustedType>(ty)->getAdjustedType();
2496 break;
2497
2498 case Type::Decayed:
2499 type = cast<DecayedType>(ty)->getPointeeType();
2500 break;
2501
2502 case Type::Pointer:
2503 type = cast<PointerType>(ty)->getPointeeType();
2504 break;
2505
2506 case Type::BlockPointer:
2507 type = cast<BlockPointerType>(ty)->getPointeeType();
2508 break;
2509
2510 case Type::LValueReference:
2511 case Type::RValueReference:
2512 type = cast<ReferenceType>(ty)->getPointeeType();
2513 break;
2514
2515 case Type::MemberPointer:
2516 type = cast<MemberPointerType>(ty)->getPointeeType();
2517 break;
2518
2519 case Type::ArrayParameter:
2520 case Type::ConstantArray:
2521 case Type::IncompleteArray:
2522 // Losing element qualification here is fine.
2523 type = cast<ArrayType>(ty)->getElementType();
2524 break;
2525
2526 case Type::VariableArray: {
2527 // Losing element qualification here is fine.
2529
2530 // Unknown size indication requires no size computation.
2531 // Otherwise, evaluate and record it.
2532 if (const Expr *sizeExpr = vat->getSizeExpr()) {
2533 // It's possible that we might have emitted this already,
2534 // e.g. with a typedef and a pointer to it.
2535 llvm::Value *&entry = VLASizeMap[sizeExpr];
2536 if (!entry) {
2537 llvm::Value *size = EmitScalarExpr(sizeExpr);
2538
2539 // C11 6.7.6.2p5:
2540 // If the size is an expression that is not an integer constant
2541 // expression [...] each time it is evaluated it shall have a value
2542 // greater than zero.
2543 if (SanOpts.has(SanitizerKind::VLABound)) {
2544 auto CheckOrdinal = SanitizerKind::SO_VLABound;
2545 auto CheckHandler = SanitizerHandler::VLABoundNotPositive;
2546 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2547 llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2548 clang::QualType SEType = sizeExpr->getType();
2549 llvm::Value *CheckCondition =
2550 SEType->isSignedIntegerType()
2551 ? Builder.CreateICmpSGT(size, Zero)
2552 : Builder.CreateICmpUGT(size, Zero);
2553 llvm::Constant *StaticArgs[] = {
2554 EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2555 EmitCheckTypeDescriptor(SEType)};
2556 EmitCheck(std::make_pair(CheckCondition, CheckOrdinal),
2557 CheckHandler, StaticArgs, size);
2558 }
2559
2560 // Always zexting here would be wrong if it weren't
2561 // undefined behavior to have a negative bound.
2562 // FIXME: What about when size's type is larger than size_t?
2563 entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2564 }
2565 }
2566 type = vat->getElementType();
2567 break;
2568 }
2569
2570 case Type::FunctionProto:
2571 case Type::FunctionNoProto:
2572 type = cast<FunctionType>(ty)->getReturnType();
2573 break;
2574
2575 case Type::Paren:
2576 case Type::TypeOf:
2577 case Type::UnaryTransform:
2578 case Type::Attributed:
2579 case Type::BTFTagAttributed:
2580 case Type::HLSLAttributedResource:
2581 case Type::SubstTemplateTypeParm:
2582 case Type::MacroQualified:
2583 case Type::CountAttributed:
2584 // Keep walking after single level desugaring.
2585 type = type.getSingleStepDesugaredType(getContext());
2586 break;
2587
2588 case Type::Typedef:
2589 case Type::Decltype:
2590 case Type::Auto:
2591 case Type::DeducedTemplateSpecialization:
2592 case Type::PackIndexing:
2593 // Stop walking: nothing to do.
2594 return;
2595
2596 case Type::TypeOfExpr:
2597 // Stop walking: emit typeof expression.
2598 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2599 return;
2600
2601 case Type::Atomic:
2602 type = cast<AtomicType>(ty)->getValueType();
2603 break;
2604
2605 case Type::Pipe:
2606 type = cast<PipeType>(ty)->getElementType();
2607 break;
2608 }
2609 } while (type->isVariablyModifiedType());
2610}
2611
2613 if (getContext().getBuiltinVaListType()->isArrayType())
2614 return EmitPointerWithAlignment(E);
2615 return EmitLValue(E).getAddress();
2616}
2617
2621
2623 const APValue &Init) {
2624 assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2625 if (CGDebugInfo *Dbg = getDebugInfo())
2626 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2627 Dbg->EmitGlobalVariable(E->getDecl(), Init);
2628}
2629
2632 // At the moment, the only aggressive peephole we do in IR gen
2633 // is trunc(zext) folding, but if we add more, we can easily
2634 // extend this protection.
2635
2636 if (!rvalue.isScalar()) return PeepholeProtection();
2637 llvm::Value *value = rvalue.getScalarVal();
2638 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2639
2640 // Just make an extra bitcast.
2641 assert(HaveInsertPoint());
2642 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2643 Builder.GetInsertBlock());
2644
2645 PeepholeProtection protection;
2646 protection.Inst = inst;
2647 return protection;
2648}
2649
2651 if (!protection.Inst) return;
2652
2653 // In theory, we could try to duplicate the peepholes now, but whatever.
2654 protection.Inst->eraseFromParent();
2655}
2656
2658 QualType Ty, SourceLocation Loc,
2659 SourceLocation AssumptionLoc,
2660 llvm::Value *Alignment,
2661 llvm::Value *OffsetValue) {
2662 if (Alignment->getType() != IntPtrTy)
2663 Alignment =
2664 Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2665 if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2666 OffsetValue =
2667 Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2668 llvm::Value *TheCheck = nullptr;
2669 if (SanOpts.has(SanitizerKind::Alignment)) {
2670 llvm::Value *PtrIntValue =
2671 Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2672
2673 if (OffsetValue) {
2674 bool IsOffsetZero = false;
2675 if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2676 IsOffsetZero = CI->isZero();
2677
2678 if (!IsOffsetZero)
2679 PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2680 }
2681
2682 llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2683 llvm::Value *Mask =
2684 Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2685 llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2686 TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2687 }
2688 llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2689 CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2690
2691 if (!SanOpts.has(SanitizerKind::Alignment))
2692 return;
2693 emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2694 OffsetValue, TheCheck, Assumption);
2695}
2696
2698 const Expr *E,
2699 SourceLocation AssumptionLoc,
2700 llvm::Value *Alignment,
2701 llvm::Value *OffsetValue) {
2702 QualType Ty = E->getType();
2703 SourceLocation Loc = E->getExprLoc();
2704
2705 emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2706 OffsetValue);
2707}
2708
2709llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2710 llvm::Value *AnnotatedVal,
2711 StringRef AnnotationStr,
2712 SourceLocation Location,
2713 const AnnotateAttr *Attr) {
2715 AnnotatedVal,
2716 CGM.EmitAnnotationString(AnnotationStr),
2717 CGM.EmitAnnotationUnit(Location),
2718 CGM.EmitAnnotationLineNo(Location),
2719 };
2720 if (Attr)
2721 Args.push_back(CGM.EmitAnnotationArgs(Attr));
2722 return Builder.CreateCall(AnnotationFn, Args);
2723}
2724
2725void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2726 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2727 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2728 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
2729 {V->getType(), CGM.ConstGlobalsPtrTy}),
2730 V, I->getAnnotation(), D->getLocation(), I);
2731}
2732
2734 Address Addr) {
2735 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2736 llvm::Value *V = Addr.emitRawPointer(*this);
2737 llvm::Type *VTy = V->getType();
2738 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2739 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2740 llvm::PointerType *IntrinTy =
2741 llvm::PointerType::get(CGM.getLLVMContext(), AS);
2742 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2743 {IntrinTy, CGM.ConstGlobalsPtrTy});
2744
2745 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2746 // FIXME Always emit the cast inst so we can differentiate between
2747 // annotation on the first field of a struct and annotation on the struct
2748 // itself.
2749 if (VTy != IntrinTy)
2750 V = Builder.CreateBitCast(V, IntrinTy);
2751 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2752 V = Builder.CreateBitCast(V, VTy);
2753 }
2754
2755 return Address(V, Addr.getElementType(), Addr.getAlignment());
2756}
2757
2759
2761 : CGF(CGF) {
2762 assert(!CGF->IsSanitizerScope);
2763 CGF->IsSanitizerScope = true;
2764}
2765
2767 CGF->IsSanitizerScope = false;
2768}
2769
2770void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2771 const llvm::Twine &Name,
2772 llvm::BasicBlock::iterator InsertPt) const {
2773 LoopStack.InsertHelper(I);
2774 if (IsSanitizerScope)
2775 I->setNoSanitizeMetadata();
2776}
2777
2779 llvm::Instruction *I, const llvm::Twine &Name,
2780 llvm::BasicBlock::iterator InsertPt) const {
2781 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2782 if (CGF)
2783 CGF->InsertHelper(I, Name, InsertPt);
2784}
2785
2786// Emits an error if we don't have a valid set of target features for the
2787// called function.
2789 const FunctionDecl *TargetDecl) {
2790 // SemaChecking cannot handle below x86 builtins because they have different
2791 // parameter ranges with different TargetAttribute of caller.
2792 if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
2793 unsigned BuiltinID = TargetDecl->getBuiltinID();
2794 if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
2795 BuiltinID == X86::BI__builtin_ia32_cmpss ||
2796 BuiltinID == X86::BI__builtin_ia32_cmppd ||
2797 BuiltinID == X86::BI__builtin_ia32_cmpsd) {
2798 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2799 llvm::StringMap<bool> TargetFetureMap;
2800 CGM.getContext().getFunctionFeatureMap(TargetFetureMap, FD);
2801 llvm::APSInt Result =
2802 *(E->getArg(2)->getIntegerConstantExpr(CGM.getContext()));
2803 if (Result.getSExtValue() > 7 && !TargetFetureMap.lookup("avx"))
2804 CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
2805 << TargetDecl->getDeclName() << "avx";
2806 }
2807 }
2808 return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2809}
2810
2811// Emits an error if we don't have a valid set of target features for the
2812// called function.
2814 const FunctionDecl *TargetDecl) {
2815 // Early exit if this is an indirect call.
2816 if (!TargetDecl)
2817 return;
2818
2819 // Get the current enclosing function if it exists. If it doesn't
2820 // we can't check the target features anyhow.
2821 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2822 if (!FD)
2823 return;
2824
2825 bool IsAlwaysInline = TargetDecl->hasAttr<AlwaysInlineAttr>();
2826 bool IsFlatten = FD && FD->hasAttr<FlattenAttr>();
2827
2828 // Grab the required features for the call. For a builtin this is listed in
2829 // the td file with the default cpu, for an always_inline function this is any
2830 // listed cpu and any listed features.
2831 unsigned BuiltinID = TargetDecl->getBuiltinID();
2832 std::string MissingFeature;
2833 llvm::StringMap<bool> CallerFeatureMap;
2834 CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2835 // When compiling in HipStdPar mode we have to be conservative in rejecting
2836 // target specific features in the FE, and defer the possible error to the
2837 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
2838 // referenced by an accelerator executable function, we emit an error.
2839 bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
2840 if (BuiltinID) {
2841 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2843 FeatureList, CallerFeatureMap) && !IsHipStdPar) {
2844 CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2845 << TargetDecl->getDeclName()
2846 << FeatureList;
2847 }
2848 } else if (!TargetDecl->isMultiVersion() &&
2849 TargetDecl->hasAttr<TargetAttr>()) {
2850 // Get the required features for the callee.
2851
2852 const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2854 CGM.getContext().filterFunctionTargetAttrs(TD);
2855
2856 SmallVector<StringRef, 1> ReqFeatures;
2857 llvm::StringMap<bool> CalleeFeatureMap;
2858 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2859
2860 for (const auto &F : ParsedAttr.Features) {
2861 if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2862 ReqFeatures.push_back(StringRef(F).substr(1));
2863 }
2864
2865 for (const auto &F : CalleeFeatureMap) {
2866 // Only positive features are "required".
2867 if (F.getValue())
2868 ReqFeatures.push_back(F.getKey());
2869 }
2870 if (!llvm::all_of(ReqFeatures,
2871 [&](StringRef Feature) {
2872 if (!CallerFeatureMap.lookup(Feature)) {
2873 MissingFeature = Feature.str();
2874 return false;
2875 }
2876 return true;
2877 }) &&
2878 !IsHipStdPar) {
2879 if (IsAlwaysInline)
2880 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2881 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2882 else if (IsFlatten)
2883 CGM.getDiags().Report(Loc, diag::err_flatten_function_needs_feature)
2884 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2885 }
2886
2887 } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) {
2888 llvm::StringMap<bool> CalleeFeatureMap;
2889 CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2890
2891 for (const auto &F : CalleeFeatureMap) {
2892 if (F.getValue() &&
2893 (!CallerFeatureMap.lookup(F.getKey()) ||
2894 !CallerFeatureMap.find(F.getKey())->getValue()) &&
2895 !IsHipStdPar) {
2896 if (IsAlwaysInline)
2897 CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2898 << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
2899 else if (IsFlatten)
2900 CGM.getDiags().Report(Loc, diag::err_flatten_function_needs_feature)
2901 << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
2902 }
2903 }
2904 }
2905}
2906
2907void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2908 if (!CGM.getCodeGenOpts().SanitizeStats)
2909 return;
2910
2911 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2912 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2913 CGM.getSanStats().create(IRB, SSK);
2914}
2915
2917 const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) {
2918 const CGCalleeInfo &CI = Callee.getAbstractInfo();
2920 if (!FP)
2921 return;
2922
2923 StringRef Salt;
2924 if (const auto &Info = FP->getExtraAttributeInfo())
2925 Salt = Info.CFISalt;
2926
2927 Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar(), Salt));
2928}
2929
2930llvm::Value *
2931CodeGenFunction::FormAArch64ResolverCondition(const FMVResolverOption &RO) {
2932 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2933}
2934
2935llvm::Value *
2936CodeGenFunction::FormX86ResolverCondition(const FMVResolverOption &RO) {
2937 llvm::Value *Condition = nullptr;
2938
2939 if (RO.Architecture) {
2940 StringRef Arch = *RO.Architecture;
2941 // If arch= specifies an x86-64 micro-architecture level, test the feature
2942 // with __builtin_cpu_supports, otherwise use __builtin_cpu_is.
2943 if (Arch.starts_with("x86-64"))
2944 Condition = EmitX86CpuSupports({Arch});
2945 else
2946 Condition = EmitX86CpuIs(Arch);
2947 }
2948
2949 if (!RO.Features.empty()) {
2950 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2951 Condition =
2952 Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2953 }
2954 return Condition;
2955}
2956
2958 llvm::Function *Resolver,
2959 CGBuilderTy &Builder,
2960 llvm::Function *FuncToReturn,
2961 bool SupportsIFunc) {
2962 if (SupportsIFunc) {
2963 Builder.CreateRet(FuncToReturn);
2964 return;
2965 }
2966
2968 llvm::make_pointer_range(Resolver->args()));
2969
2970 llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2971 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2972
2973 if (Resolver->getReturnType()->isVoidTy())
2974 Builder.CreateRetVoid();
2975 else
2976 Builder.CreateRet(Result);
2977}
2978
2980 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
2981
2982 llvm::Triple::ArchType ArchType =
2983 getContext().getTargetInfo().getTriple().getArch();
2984
2985 switch (ArchType) {
2986 case llvm::Triple::x86:
2987 case llvm::Triple::x86_64:
2988 EmitX86MultiVersionResolver(Resolver, Options);
2989 return;
2990 case llvm::Triple::aarch64:
2991 EmitAArch64MultiVersionResolver(Resolver, Options);
2992 return;
2993 case llvm::Triple::riscv32:
2994 case llvm::Triple::riscv64:
2995 EmitRISCVMultiVersionResolver(Resolver, Options);
2996 return;
2997
2998 default:
2999 assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
3000 }
3001}
3002
3004 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3005
3006 if (getContext().getTargetInfo().getTriple().getOS() !=
3007 llvm::Triple::OSType::Linux) {
3008 CGM.getDiags().Report(diag::err_os_unsupport_riscv_fmv);
3009 return;
3010 }
3011
3012 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3013 Builder.SetInsertPoint(CurBlock);
3015
3016 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3017 bool HasDefault = false;
3018 unsigned DefaultIndex = 0;
3019
3020 // Check the each candidate function.
3021 for (unsigned Index = 0; Index < Options.size(); Index++) {
3022
3023 if (Options[Index].Features.empty()) {
3024 HasDefault = true;
3025 DefaultIndex = Index;
3026 continue;
3027 }
3028
3029 Builder.SetInsertPoint(CurBlock);
3030
3031 // FeaturesCondition: The bitmask of the required extension has been
3032 // enabled by the runtime object.
3033 // (__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
3034 // REQUIRED_BITMASK
3035 //
3036 // When condition is met, return this version of the function.
3037 // Otherwise, try the next version.
3038 //
3039 // if (FeaturesConditionVersion1)
3040 // return Version1;
3041 // else if (FeaturesConditionVersion2)
3042 // return Version2;
3043 // else if (FeaturesConditionVersion3)
3044 // return Version3;
3045 // ...
3046 // else
3047 // return DefaultVersion;
3048
3049 // TODO: Add a condition to check the length before accessing elements.
3050 // Without checking the length first, we may access an incorrect memory
3051 // address when using different versions.
3052 llvm::SmallVector<StringRef, 8> CurrTargetAttrFeats;
3053 llvm::SmallVector<std::string, 8> TargetAttrFeats;
3054
3055 for (StringRef Feat : Options[Index].Features) {
3056 std::vector<std::string> FeatStr =
3058
3059 assert(FeatStr.size() == 1 && "Feature string not delimited");
3060
3061 std::string &CurrFeat = FeatStr.front();
3062 if (CurrFeat[0] == '+')
3063 TargetAttrFeats.push_back(CurrFeat.substr(1));
3064 }
3065
3066 if (TargetAttrFeats.empty())
3067 continue;
3068
3069 for (std::string &Feat : TargetAttrFeats)
3070 CurrTargetAttrFeats.push_back(Feat);
3071
3072 Builder.SetInsertPoint(CurBlock);
3073 llvm::Value *FeatsCondition = EmitRISCVCpuSupports(CurrTargetAttrFeats);
3074
3075 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3076 CGBuilderTy RetBuilder(*this, RetBlock);
3077 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder,
3078 Options[Index].Function, SupportsIFunc);
3079 llvm::BasicBlock *ElseBlock = createBasicBlock("resolver_else", Resolver);
3080
3081 Builder.SetInsertPoint(CurBlock);
3082 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
3083
3084 CurBlock = ElseBlock;
3085 }
3086
3087 // Finally, emit the default one.
3088 if (HasDefault) {
3089 Builder.SetInsertPoint(CurBlock);
3091 CGM, Resolver, Builder, Options[DefaultIndex].Function, SupportsIFunc);
3092 return;
3093 }
3094
3095 // If no generic/default, emit an unreachable.
3096 Builder.SetInsertPoint(CurBlock);
3097 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3098 TrapCall->setDoesNotReturn();
3099 TrapCall->setDoesNotThrow();
3100 Builder.CreateUnreachable();
3101 Builder.ClearInsertionPoint();
3102}
3103
3105 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3106 assert(!Options.empty() && "No multiversion resolver options found");
3107 assert(Options.back().Features.size() == 0 && "Default case must be last");
3108 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3109 assert(SupportsIFunc &&
3110 "Multiversion resolver requires target IFUNC support");
3111 bool AArch64CpuInitialized = false;
3112 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3113
3114 for (const FMVResolverOption &RO : Options) {
3115 Builder.SetInsertPoint(CurBlock);
3116 llvm::Value *Condition = FormAArch64ResolverCondition(RO);
3117
3118 // The 'default' or 'all features enabled' case.
3119 if (!Condition) {
3120 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3121 SupportsIFunc);
3122 return;
3123 }
3124
3125 if (!AArch64CpuInitialized) {
3126 Builder.SetInsertPoint(CurBlock, CurBlock->begin());
3127 EmitAArch64CpuInit();
3128 AArch64CpuInitialized = true;
3129 Builder.SetInsertPoint(CurBlock);
3130 }
3131
3132 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3133 CGBuilderTy RetBuilder(*this, RetBlock);
3134 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3135 SupportsIFunc);
3136 CurBlock = createBasicBlock("resolver_else", Resolver);
3137 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3138 }
3139
3140 // If no default, emit an unreachable.
3141 Builder.SetInsertPoint(CurBlock);
3142 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3143 TrapCall->setDoesNotReturn();
3144 TrapCall->setDoesNotThrow();
3145 Builder.CreateUnreachable();
3146 Builder.ClearInsertionPoint();
3147}
3148
3150 llvm::Function *Resolver, ArrayRef<FMVResolverOption> Options) {
3151
3152 bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
3153
3154 // Main function's basic block.
3155 llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
3156 Builder.SetInsertPoint(CurBlock);
3157 EmitX86CpuInit();
3158
3159 for (const FMVResolverOption &RO : Options) {
3160 Builder.SetInsertPoint(CurBlock);
3161 llvm::Value *Condition = FormX86ResolverCondition(RO);
3162
3163 // The 'default' or 'generic' case.
3164 if (!Condition) {
3165 assert(&RO == Options.end() - 1 &&
3166 "Default or Generic case must be last");
3167 CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
3168 SupportsIFunc);
3169 return;
3170 }
3171
3172 llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
3173 CGBuilderTy RetBuilder(*this, RetBlock);
3174 CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
3175 SupportsIFunc);
3176 CurBlock = createBasicBlock("resolver_else", Resolver);
3177 Builder.CreateCondBr(Condition, RetBlock, CurBlock);
3178 }
3179
3180 // If no generic/default, emit an unreachable.
3181 Builder.SetInsertPoint(CurBlock);
3182 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3183 TrapCall->setDoesNotReturn();
3184 TrapCall->setDoesNotThrow();
3185 Builder.CreateUnreachable();
3186 Builder.ClearInsertionPoint();
3187}
3188
3189// Loc - where the diagnostic will point, where in the source code this
3190// alignment has failed.
3191// SecondaryLoc - if present (will be present if sufficiently different from
3192// Loc), the diagnostic will additionally point a "Note:" to this location.
3193// It should be the location where the __attribute__((assume_aligned))
3194// was written e.g.
3196 llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
3197 SourceLocation SecondaryLoc, llvm::Value *Alignment,
3198 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3199 llvm::Instruction *Assumption) {
3200 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3201 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3202 llvm::Intrinsic::getOrInsertDeclaration(
3203 Builder.GetInsertBlock()->getParent()->getParent(),
3204 llvm::Intrinsic::assume) &&
3205 "Assumption should be a call to llvm.assume().");
3206 assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
3207 "Assumption should be the last instruction of the basic block, "
3208 "since the basic block is still being generated.");
3209
3210 if (!SanOpts.has(SanitizerKind::Alignment))
3211 return;
3212
3213 // Don't check pointers to volatile data. The behavior here is implementation-
3214 // defined.
3216 return;
3217
3218 // We need to temorairly remove the assumption so we can insert the
3219 // sanitizer check before it, else the check will be dropped by optimizations.
3220 Assumption->removeFromParent();
3221
3222 {
3223 auto CheckOrdinal = SanitizerKind::SO_Alignment;
3224 auto CheckHandler = SanitizerHandler::AlignmentAssumption;
3225 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
3226
3227 if (!OffsetValue)
3228 OffsetValue = Builder.getInt1(false); // no offset.
3229
3230 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
3231 EmitCheckSourceLocation(SecondaryLoc),
3233 llvm::Value *DynamicData[] = {Ptr, Alignment, OffsetValue};
3234 EmitCheck({std::make_pair(TheCheck, CheckOrdinal)}, CheckHandler,
3235 StaticData, DynamicData);
3236 }
3237
3238 // We are now in the (new, empty) "cont" basic block.
3239 // Reintroduce the assumption.
3240 Builder.Insert(Assumption);
3241 // FIXME: Assumption still has it's original basic block as it's Parent.
3242}
3243
3245 if (CGDebugInfo *DI = getDebugInfo())
3246 return DI->SourceLocToDebugLoc(Location);
3247
3248 return llvm::DebugLoc();
3249}
3250
3251llvm::Value *
3252CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3253 Stmt::Likelihood LH) {
3254 switch (LH) {
3255 case Stmt::LH_None:
3256 return Cond;
3257 case Stmt::LH_Likely:
3258 case Stmt::LH_Unlikely:
3259 // Don't generate llvm.expect on -O0 as the backend won't use it for
3260 // anything.
3261 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3262 return Cond;
3263 llvm::Type *CondTy = Cond->getType();
3264 assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
3265 llvm::Function *FnExpect =
3266 CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
3267 llvm::Value *ExpectedValueOfCond =
3268 llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
3269 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3270 Cond->getName() + ".expval");
3271 }
3272 llvm_unreachable("Unknown Likelihood");
3273}
3274
3275llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec,
3276 unsigned NumElementsDst,
3277 const llvm::Twine &Name) {
3278 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3279 unsigned NumElementsSrc = SrcTy->getNumElements();
3280 if (NumElementsSrc == NumElementsDst)
3281 return SrcVec;
3282
3283 std::vector<int> ShuffleMask(NumElementsDst, -1);
3284 for (unsigned MaskIdx = 0;
3285 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3286 ShuffleMask[MaskIdx] = MaskIdx;
3287
3288 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3289}
3290
3292 const CGPointerAuthInfo &PointerAuth,
3294 if (!PointerAuth.isSigned())
3295 return;
3296
3297 auto *Key = Builder.getInt32(PointerAuth.getKey());
3298
3299 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3300 if (!Discriminator)
3301 Discriminator = Builder.getSize(0);
3302
3303 llvm::Value *Args[] = {Key, Discriminator};
3304 Bundles.emplace_back("ptrauth", Args);
3305}
3306
3308 const CGPointerAuthInfo &PointerAuth,
3309 llvm::Value *Pointer,
3310 unsigned IntrinsicID) {
3311 if (!PointerAuth)
3312 return Pointer;
3313
3314 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3315
3316 llvm::Value *Discriminator = PointerAuth.getDiscriminator();
3317 if (!Discriminator) {
3318 Discriminator = CGF.Builder.getSize(0);
3319 }
3320
3321 // Convert the pointer to intptr_t before signing it.
3322 auto OrigType = Pointer->getType();
3323 Pointer = CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy);
3324
3325 // call i64 @llvm.ptrauth.sign.i64(i64 %pointer, i32 %key, i64 %discriminator)
3326 auto Intrinsic = CGF.CGM.getIntrinsic(IntrinsicID);
3327 Pointer = CGF.EmitRuntimeCall(Intrinsic, {Pointer, Key, Discriminator});
3328
3329 // Convert back to the original type.
3330 Pointer = CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3331 return Pointer;
3332}
3333
3334llvm::Value *
3336 llvm::Value *Pointer) {
3337 if (!PointerAuth.shouldSign())
3338 return Pointer;
3339 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3340 llvm::Intrinsic::ptrauth_sign);
3341}
3342
3343static llvm::Value *EmitStrip(CodeGenFunction &CGF,
3344 const CGPointerAuthInfo &PointerAuth,
3345 llvm::Value *Pointer) {
3346 auto StripIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3347
3348 auto Key = CGF.Builder.getInt32(PointerAuth.getKey());
3349 // Convert the pointer to intptr_t before signing it.
3350 auto OrigType = Pointer->getType();
3352 StripIntrinsic, {CGF.Builder.CreatePtrToInt(Pointer, CGF.IntPtrTy), Key});
3353 return CGF.Builder.CreateIntToPtr(Pointer, OrigType);
3354}
3355
3356llvm::Value *
3358 llvm::Value *Pointer) {
3359 if (PointerAuth.shouldStrip()) {
3360 return EmitStrip(*this, PointerAuth, Pointer);
3361 }
3362 if (!PointerAuth.shouldAuth()) {
3363 return Pointer;
3364 }
3365
3366 return EmitPointerAuthCommon(*this, PointerAuth, Pointer,
3367 llvm::Intrinsic::ptrauth_auth);
3368}
3369
3371 llvm::Instruction *KeyInstruction, llvm::Value *Backup) {
3372 if (CGDebugInfo *DI = getDebugInfo())
3373 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3374}
3375
3377 llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom) {
3378 if (CGDebugInfo *DI = getDebugInfo())
3379 DI->addInstToSpecificSourceAtom(KeyInstruction, Backup, Atom);
3380}
3381
3382void CodeGenFunction::addInstToNewSourceAtom(llvm::Instruction *KeyInstruction,
3383 llvm::Value *Backup) {
3384 if (CGDebugInfo *DI = getDebugInfo()) {
3386 DI->addInstToCurrentSourceAtom(KeyInstruction, Backup);
3387 }
3388}
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....
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:188
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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.
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:856
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
QualType getElementType() const
Definition TypeBase.h:3732
Attr - This represents one attribute.
Definition Attr.h:44
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3974
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4107
BinaryOperatorKind Opcode
Definition Expr.h:3979
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2710
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2809
bool isStatic() const
Definition DeclCXX.cpp:2401
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
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:1784
bool isCapturelessLambda() const
Definition DeclCXX.h:1064
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1209
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3083
SourceLocation getBeginLoc() const
Definition Expr.h:3213
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
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:103
@ 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:41
const FunctionProtoType * getCalleeFunctionProtoType() const
Definition CGCall.h:56
All available information about a concrete callee.
Definition CGCall.h:63
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
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:274
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
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...
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...
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:181
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.
bool ShouldSkipSanitizerInstrumentation()
ShouldSkipSanitizerInstrumentation - Return true if the current function should not be instrumented w...
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
llvm::Value * EmitRISCVCpuSupports(const CallExpr *E)
Definition RISCV.cpp:970
llvm::Value * EmitRISCVCpuInit()
Definition RISCV.cpp:960
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:3113
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:706
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:6631
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:3648
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:830
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.
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:3538
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:174
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:578
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:242
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2336
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.
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:223
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:3788
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
SmallVector< const BinaryOperator *, 16 > MCDCLogOpStack
Stack to track the Logical Operator recursion nest for MC/DC.
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:1446
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:5215
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount=0, Stmt::Likelihood LH=Stmt::LH_None, const Expr *CntrIdx=nullptr)
EmitBranchToCounterBlock - Emit a conditional branch to a new block that increments a profile counter...
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
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:3080
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:3169
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:61
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:5164
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:1563
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:3967
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:1515
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:672
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,...
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:4213
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:1631
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 emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
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:2073
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:652
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:391
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:375
LValue - This represents an lvalue references.
Definition CGValue.h:182
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:361
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:71
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
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:241
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
ConditionalOperator - The ?
Definition Expr.h:4327
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1272
ValueDecl * getDecl()
Definition Expr.h:1340
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
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:559
SourceLocation getLocation() const
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:577
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:3922
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3157
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3271
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition Decl.h:2906
bool usesSEHTry() const
Indicates the function uses __try.
Definition Decl.h:2517
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
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:4205
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3131
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3363
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition Decl.cpp:3514
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2427
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3356
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2384
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
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:5264
QualType desugar() const
Definition TypeBase.h:5845
FunctionTypeExtraAttributeInfo getExtraAttributeInfo() const
Return the extra attribute information.
Definition TypeBase.h:5753
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
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, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5470
Represents the declaration of a label.
Definition Decl.h:523
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:339
Represents a parameter to a function.
Definition Decl.h:1789
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
@ 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:8369
field_range fields() const
Definition Decl.h:4512
Encodes a location in the source.
A trivial tuple used to represent a source range.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:295
StmtClass getStmtClass() const
Definition Stmt.h:1472
Likelihood
The likelihood of a branch being taken.
Definition Stmt.h:1415
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
Definition Stmt.h:1416
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
Definition Stmt.h:1417
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1419
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:8878
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
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:752
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isObjCRetainableType() const
Definition Type.cpp:5291
bool isFunctionNoProtoType() const
Definition TypeBase.h:2600
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2246
QualType getType() const
Definition Decl.h:722
Represents a variable declaration or definition.
Definition Decl.h:925
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
QualType getElementType() const
Definition TypeBase.h:4187
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:154
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:145
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
CGBuilderInserter CGBuilderInserterTy
Definition CGBuilder.h:45
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
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
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
const FunctionProtoType * T
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:5967
@ Other
Other implicit parameter.
Definition Decl.h:1745
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
Definition Sema.h:437
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
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:645
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5001
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