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