Debian Codegraph @

clang/lib/CodeGen/CodeGenFunction.cpp

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