Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp
Line
Count
Source (jump to first uncovered line)
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 "CGOpenMPRuntime.h"
20
#include "CodeGenModule.h"
21
#include "CodeGenPGO.h"
22
#include "TargetInfo.h"
23
#include "clang/AST/ASTContext.h"
24
#include "clang/AST/ASTLambda.h"
25
#include "clang/AST/Attr.h"
26
#include "clang/AST/Decl.h"
27
#include "clang/AST/DeclCXX.h"
28
#include "clang/AST/Expr.h"
29
#include "clang/AST/StmtCXX.h"
30
#include "clang/AST/StmtObjC.h"
31
#include "clang/Basic/Builtins.h"
32
#include "clang/Basic/CodeGenOptions.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/CodeGen/CGFunctionInfo.h"
35
#include "clang/Frontend/FrontendDiagnostic.h"
36
#include "llvm/ADT/ArrayRef.h"
37
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
38
#include "llvm/IR/DataLayout.h"
39
#include "llvm/IR/Dominators.h"
40
#include "llvm/IR/FPEnv.h"
41
#include "llvm/IR/IntrinsicInst.h"
42
#include "llvm/IR/Intrinsics.h"
43
#include "llvm/IR/MDBuilder.h"
44
#include "llvm/IR/Operator.h"
45
#include "llvm/Support/CRC.h"
46
#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
47
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
48
49
using namespace clang;
50
using namespace CodeGen;
51
52
/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
53
/// markers.
54
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
55
313k
                                      const LangOptions &LangOpts) {
56
313k
  if (CGOpts.DisableLifetimeMarkers)
57
7
    return false;
58
59
  // Sanitizers may use markers.
60
313k
  if (CGOpts.SanitizeAddressUseAfterScope ||
61
313k
      
LangOpts.Sanitize.has(SanitizerKind::HWAddress)312k
||
62
313k
      
LangOpts.Sanitize.has(SanitizerKind::Memory)312k
)
63
930
    return true;
64
65
  // For now, only in optimized builds.
66
312k
  return CGOpts.OptimizationLevel != 0;
67
313k
}
68
69
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
70
    : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
71
      Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
72
              CGBuilderInserterTy(this)),
73
      SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
74
      DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
75
      ShouldEmitLifetimeMarkers(
76
313k
          shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
77
313k
  if (!suppressNewContext)
78
287k
    CGM.getCXXABI().getMangleContext().startNewFunction();
79
313k
  EHStack.setCGF(this);
80
81
313k
  SetFastMathFlags(CurFPFeatures);
82
313k
}
83
84
313k
CodeGenFunction::~CodeGenFunction() {
85
313k
  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
86
87
313k
  if (getLangOpts().OpenMP && 
CurFn70.1k
)
88
70.1k
    CGM.getOpenMPRuntime().functionFinished(*this);
89
90
  // If we have an OpenMPIRBuilder we want to finalize functions (incl.
91
  // outlining etc) at some point. Doing it once the function codegen is done
92
  // seems to be a reasonable spot. We do it here, as opposed to the deletion
93
  // time of the CodeGenModule, because we have to ensure the IR has not yet
94
  // been "emitted" to the outside, thus, modifications are still sensible.
95
313k
  if (CGM.getLangOpts().OpenMPIRBuilder && 
CurFn359
)
96
359
    CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
97
313k
}
98
99
// Map the LangOption for exception behavior into
100
// the corresponding enum in the IR.
101
llvm::fp::ExceptionBehavior
102
314k
clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
103
104
314k
  switch (Kind) {
105
311k
  case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
106
624
  case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
107
2.43k
  case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
108
314k
  }
109
0
  llvm_unreachable("Unsupported FP Exception Behavior");
110
0
}
111
112
315k
void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
113
315k
  llvm::FastMathFlags FMF;
114
315k
  FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
115
315k
  FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
116
315k
  FMF.setNoInfs(FPFeatures.getNoHonorInfs());
117
315k
  FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
118
315k
  FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
119
315k
  FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
120
315k
  FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
121
315k
  Builder.setFastMathFlags(FMF);
122
315k
}
123
124
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
125
                                                  const Expr *E)
126
191k
    : CGF(CGF) {
127
191k
  ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
128
191k
}
129
130
CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
131
                                                  FPOptions FPFeatures)
132
32.0k
    : CGF(CGF) {
133
32.0k
  ConstructorHelper(FPFeatures);
134
32.0k
}
135
136
223k
void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
137
223k
  OldFPFeatures = CGF.CurFPFeatures;
138
223k
  CGF.CurFPFeatures = FPFeatures;
139
140
223k
  OldExcept = CGF.Builder.getDefaultConstrainedExcept();
141
223k
  OldRounding = CGF.Builder.getDefaultConstrainedRounding();
142
143
223k
  if (OldFPFeatures == FPFeatures)
144
221k
    return;
145
146
2.02k
  FMFGuard.emplace(CGF.Builder);
147
148
2.02k
  llvm::RoundingMode NewRoundingBehavior =
149
2.02k
      static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
150
2.02k
  CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
151
2.02k
  auto NewExceptionBehavior =
152
2.02k
      ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
153
2.02k
          FPFeatures.getFPExceptionMode()));
154
2.02k
  CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
155
156
2.02k
  CGF.SetFastMathFlags(FPFeatures);
157
158
2.02k
  assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
159
2.02k
          isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
160
2.02k
          isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
161
2.02k
          (NewExceptionBehavior == llvm::fp::ebIgnore &&
162
2.02k
           NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
163
2.02k
         "FPConstrained should be enabled on entire function");
164
165
8.11k
  auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
166
8.11k
    auto OldValue =
167
8.11k
        CGF.CurFn->getFnAttribute(Name).getValueAsBool();
168
8.11k
    auto NewValue = OldValue & Value;
169
8.11k
    if (OldValue != NewValue)
170
53
      CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
171
8.11k
  };
172
2.02k
  mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
173
2.02k
  mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
174
2.02k
  mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
175
2.02k
  mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
176
2.02k
                                         
FPFeatures.getAllowReciprocal()120
&&
177
2.02k
                                         
FPFeatures.getAllowApproxFunc()72
&&
178
2.02k
                                         
FPFeatures.getNoSignedZero()72
);
179
2.02k
}
180
181
223k
CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
182
223k
  CGF.CurFPFeatures = OldFPFeatures;
183
223k
  CGF.Builder.setDefaultConstrainedExcept(OldExcept);
184
223k
  CGF.Builder.setDefaultConstrainedRounding(OldRounding);
185
223k
}
186
187
41.1k
LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
188
41.1k
  LValueBaseInfo BaseInfo;
189
41.1k
  TBAAAccessInfo TBAAInfo;
190
41.1k
  CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
191
41.1k
  Address Addr(V, ConvertTypeForMem(T), Alignment);
192
41.1k
  return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
193
41.1k
}
194
195
/// Given a value of type T* that may not be to a complete object,
196
/// construct an l-value with the natural pointee alignment of T.
197
LValue
198
64.5k
CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
199
64.5k
  LValueBaseInfo BaseInfo;
200
64.5k
  TBAAAccessInfo TBAAInfo;
201
64.5k
  CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
202
64.5k
                                                /* forPointeeType= */ true);
203
64.5k
  Address Addr(V, ConvertTypeForMem(T), Align);
204
64.5k
  return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
205
64.5k
}
206
207
208
1.62M
llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
209
1.62M
  return CGM.getTypes().ConvertTypeForMem(T);
210
1.62M
}
211
212
3.36M
llvm::Type *CodeGenFunction::ConvertType(QualType T) {
213
3.36M
  return CGM.getTypes().ConvertType(T);
214
3.36M
}
215
216
6.09M
TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
217
6.09M
  type = type.getCanonicalType();
218
6.09M
  while (true) {
219
6.09M
    switch (type->getTypeClass()) {
220
0
#define TYPE(name, parent)
221
0
#define ABSTRACT_TYPE(name, parent)
222
0
#define NON_CANONICAL_TYPE(name, parent) case Type::name:
223
0
#define DEPENDENT_TYPE(name, parent) case Type::name:
224
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
225
0
#include "clang/AST/TypeNodes.inc"
226
0
      llvm_unreachable("non-canonical or dependent type in IR-generation");
227
228
0
    case Type::Auto:
229
0
    case Type::DeducedTemplateSpecialization:
230
0
      llvm_unreachable("undeduced type in IR-generation");
231
232
    // Various scalar types.
233
3.09M
    case Type::Builtin:
234
4.98M
    case Type::Pointer:
235
4.98M
    case Type::BlockPointer:
236
5.17M
    case Type::LValueReference:
237
5.23M
    case Type::RValueReference:
238
5.23M
    case Type::MemberPointer:
239
5.69M
    case Type::Vector:
240
5.70M
    case Type::ExtVector:
241
5.70M
    case Type::ConstantMatrix:
242
5.70M
    case Type::FunctionProto:
243
5.70M
    case Type::FunctionNoProto:
244
5.71M
    case Type::Enum:
245
5.84M
    case Type::ObjCObjectPointer:
246
5.84M
    case Type::Pipe:
247
5.85M
    case Type::BitInt:
248
5.85M
      return TEK_Scalar;
249
250
    // Complexes.
251
7.34k
    case Type::Complex:
252
7.34k
      return TEK_Complex;
253
254
    // Arrays, records, and Objective-C objects.
255
5.44k
    case Type::ConstantArray:
256
5.44k
    case Type::IncompleteArray:
257
5.47k
    case Type::VariableArray:
258
236k
    case Type::Record:
259
236k
    case Type::ObjCObject:
260
236k
    case Type::ObjCInterface:
261
236k
      return TEK_Aggregate;
262
263
    // We operate on atomic values according to their underlying type.
264
314
    case Type::Atomic:
265
314
      type = cast<AtomicType>(type)->getValueType();
266
314
      continue;
267
6.09M
    }
268
0
    llvm_unreachable("unknown type kind!");
269
0
  }
270
6.09M
}
271
272
312k
llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
273
  // For cleanliness, we try to avoid emitting the return block for
274
  // simple cases.
275
312k
  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
276
277
312k
  if (CurBB) {
278
160k
    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
279
280
    // We have a valid insert point, reuse it if it is empty or there are no
281
    // explicit jumps to the return block.
282
160k
    if (CurBB->empty() || 
ReturnBlock.getBlock()->use_empty()133k
) {
283
160k
      ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
284
160k
      delete ReturnBlock.getBlock();
285
160k
      ReturnBlock = JumpDest();
286
160k
    } else
287
36
      EmitBlock(ReturnBlock.getBlock());
288
160k
    return llvm::DebugLoc();
289
160k
  }
290
291
  // Otherwise, if the return block is the target of a single direct
292
  // branch then we can just put the code in that block instead. This
293
  // cleans up functions which started with a unified return block.
294
151k
  if (ReturnBlock.getBlock()->hasOneUse()) {
295
148k
    llvm::BranchInst *BI =
296
148k
      dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
297
148k
    if (BI && 
BI->isUnconditional()148k
&&
298
148k
        
BI->getSuccessor(0) == ReturnBlock.getBlock()148k
) {
299
      // Record/return the DebugLoc of the simple 'return' expression to be used
300
      // later by the actual 'ret' instruction.
301
148k
      llvm::DebugLoc Loc = BI->getDebugLoc();
302
148k
      Builder.SetInsertPoint(BI->getParent());
303
148k
      BI->eraseFromParent();
304
148k
      delete ReturnBlock.getBlock();
305
148k
      ReturnBlock = JumpDest();
306
148k
      return Loc;
307
148k
    }
308
148k
  }
309
310
  // FIXME: We are at an unreachable point, there is no reason to emit the block
311
  // unless it has uses. However, we still need a place to put the debug
312
  // region.end for now.
313
314
3.19k
  EmitBlock(ReturnBlock.getBlock());
315
3.19k
  return llvm::DebugLoc();
316
151k
}
317
318
1.24M
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
319
1.24M
  if (!BB) 
return1.24M
;
320
8.74k
  if (!BB->use_empty())
321
8.74k
    return CGF.CurFn->getBasicBlockList().push_back(BB);
322
8
  delete BB;
323
8
}
324
325
312k
void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
326
312k
  assert(BreakContinueStack.empty() &&
327
312k
         "mismatched push/pop in break/continue stack!");
328
329
312k
  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
330
312k
    && 
NumSimpleReturnExprs == NumReturnExprs14.8k
331
312k
    && 
ReturnBlock.getBlock()->use_empty()13.5k
;
332
  // Usually the return expression is evaluated before the cleanup
333
  // code.  If the function contains only a simple return statement,
334
  // such as a constant, the location before the cleanup code becomes
335
  // the last useful breakpoint in the function, because the simple
336
  // return expression will be evaluated after the cleanup code. To be
337
  // safe, set the debug location for cleanup code to the location of
338
  // the return statement.  Otherwise the cleanup code should be at the
339
  // end of the function's lexical scope.
340
  //
341
  // If there are multiple branches to the return block, the branch
342
  // instructions will get the location of the return statements and
343
  // all will be fine.
344
312k
  if (CGDebugInfo *DI = getDebugInfo()) {
345
103k
    if (OnlySimpleReturnStmts)
346
619
      DI->EmitLocation(Builder, LastStopPoint);
347
103k
    else
348
103k
      DI->EmitLocation(Builder, EndLoc);
349
103k
  }
350
351
  // Pop any cleanups that might have been associated with the
352
  // parameters.  Do this in whatever block we're currently in; it's
353
  // important to do this before we enter the return block or return
354
  // edges will be *really* confused.
355
312k
  bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
356
312k
  bool HasOnlyLifetimeMarkers =
357
312k
      HasCleanups && 
EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth)7.34k
;
358
312k
  bool EmitRetDbgLoc = !HasCleanups || 
HasOnlyLifetimeMarkers7.34k
;
359
312k
  if (HasCleanups) {
360
    // Make sure the line table doesn't jump back into the body for
361
    // the ret after it's been at EndLoc.
362
7.34k
    Optional<ApplyDebugLocation> AL;
363
7.34k
    if (CGDebugInfo *DI = getDebugInfo()) {
364
1.79k
      if (OnlySimpleReturnStmts)
365
619
        DI->EmitLocation(Builder, EndLoc);
366
1.17k
      else
367
        // We may not have a valid end location. Try to apply it anyway, and
368
        // fall back to an artificial location if needed.
369
1.17k
        AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
370
1.79k
    }
371
372
7.34k
    PopCleanupBlocks(PrologueCleanupDepth);
373
7.34k
  }
374
375
  // Emit function epilog (to return).
376
312k
  llvm::DebugLoc Loc = EmitReturnBlock();
377
378
312k
  if (ShouldInstrumentFunction()) {
379
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
380
7
      CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
381
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
382
2
      CurFn->addFnAttr("instrument-function-exit-inlined",
383
2
                       "__cyg_profile_func_exit");
384
11
  }
385
386
312k
  if (ShouldSkipSanitizerInstrumentation())
387
6
    CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
388
389
  // Emit debug descriptor for function end.
390
312k
  if (CGDebugInfo *DI = getDebugInfo())
391
103k
    DI->EmitFunctionEnd(Builder, CurFn);
392
393
  // Reset the debug location to that of the simple 'return' expression, if any
394
  // rather than that of the end of the function's scope '}'.
395
312k
  ApplyDebugLocation AL(*this, Loc);
396
312k
  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
397
312k
  EmitEndEHSpec(CurCodeDecl);
398
399
312k
  assert(EHStack.empty() &&
400
312k
         "did not remove all scopes from cleanup stack!");
401
402
  // If someone did an indirect goto, emit the indirect goto block at the end of
403
  // the function.
404
312k
  if (IndirectBranch) {
405
39
    EmitBlock(IndirectBranch->getParent());
406
39
    Builder.ClearInsertionPoint();
407
39
  }
408
409
  // If some of our locals escaped, insert a call to llvm.localescape in the
410
  // entry block.
411
312k
  if (!EscapedLocals.empty()) {
412
    // Invert the map from local to index into a simple vector. There should be
413
    // no holes.
414
38
    SmallVector<llvm::Value *, 4> EscapeArgs;
415
38
    EscapeArgs.resize(EscapedLocals.size());
416
38
    for (auto &Pair : EscapedLocals)
417
46
      EscapeArgs[Pair.second] = Pair.first;
418
38
    llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
419
38
        &CGM.getModule(), llvm::Intrinsic::localescape);
420
38
    CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
421
38
  }
422
423
  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
424
312k
  llvm::Instruction *Ptr = AllocaInsertPt;
425
312k
  AllocaInsertPt = nullptr;
426
312k
  Ptr->eraseFromParent();
427
428
  // PostAllocaInsertPt, if created, was lazily created when it was required,
429
  // remove it now since it was just created for our own convenience.
430
312k
  if (PostAllocaInsertPt) {
431
1.41k
    llvm::Instruction *PostPtr = PostAllocaInsertPt;
432
1.41k
    PostAllocaInsertPt = nullptr;
433
1.41k
    PostPtr->eraseFromParent();
434
1.41k
  }
435
436
  // If someone took the address of a label but never did an indirect goto, we
437
  // made a zero entry PHI node, which is illegal, zap it now.
438
312k
  if (IndirectBranch) {
439
39
    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
440
39
    if (PN->getNumIncomingValues() == 0) {
441
19
      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
442
19
      PN->eraseFromParent();
443
19
    }
444
39
  }
445
446
312k
  EmitIfUsed(*this, EHResumeBlock);
447
312k
  EmitIfUsed(*this, TerminateLandingPad);
448
312k
  EmitIfUsed(*this, TerminateHandler);
449
312k
  EmitIfUsed(*this, UnreachableBlock);
450
451
312k
  for (const auto &FuncletAndParent : TerminateFunclets)
452
15
    EmitIfUsed(*this, FuncletAndParent.second);
453
454
312k
  if (CGM.getCodeGenOpts().EmitDeclMetadata)
455
22.7k
    EmitDeclMetadata();
456
457
312k
  for (const auto &R : DeferredReplacements) {
458
103
    if (llvm::Value *Old = R.first) {
459
102
      Old->replaceAllUsesWith(R.second);
460
102
      cast<llvm::Instruction>(Old)->eraseFromParent();
461
102
    }
462
103
  }
463
312k
  DeferredReplacements.clear();
464
465
  // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
466
  // PHIs if the current function is a coroutine. We don't do it for all
467
  // functions as it may result in slight increase in numbers of instructions
468
  // if compiled with no optimizations. We do it for coroutine as the lifetime
469
  // of CleanupDestSlot alloca make correct coroutine frame building very
470
  // difficult.
471
312k
  if (NormalCleanupDest.isValid() && 
isCoroutine()357
) {
472
120
    llvm::DominatorTree DT(*CurFn);
473
120
    llvm::PromoteMemToReg(
474
120
        cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
475
120
    NormalCleanupDest = Address::invalid();
476
120
  }
477
478
  // Scan function arguments for vector width.
479
312k
  for (llvm::Argument &A : CurFn->args())
480
518k
    if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
481
123k
      LargestVectorWidth =
482
123k
          std::max((uint64_t)LargestVectorWidth,
483
123k
                   VT->getPrimitiveSizeInBits().getKnownMinSize());
484
485
  // Update vector width based on return type.
486
312k
  if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
487
56.2k
    LargestVectorWidth =
488
56.2k
        std::max((uint64_t)LargestVectorWidth,
489
56.2k
                 VT->getPrimitiveSizeInBits().getKnownMinSize());
490
491
  // Add the required-vector-width attribute. This contains the max width from:
492
  // 1. min-vector-width attribute used in the source program.
493
  // 2. Any builtins used that have a vector width specified.
494
  // 3. Values passed in and out of inline assembly.
495
  // 4. Width of vector arguments and return types for this function.
496
  // 5. Width of vector aguments and return types for functions called by this
497
  //    function.
498
312k
  CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
499
500
  // Add vscale_range attribute if appropriate.
501
312k
  Optional<std::pair<unsigned, unsigned>> VScaleRange =
502
312k
      getContext().getTargetInfo().getVScaleRange(getLangOpts());
503
312k
  if (VScaleRange) {
504
29.8k
    CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
505
29.8k
        getLLVMContext(), VScaleRange.getValue().first,
506
29.8k
        VScaleRange.getValue().second));
507
29.8k
  }
508
509
  // If we generated an unreachable return block, delete it now.
510
312k
  if (ReturnBlock.isValid() && 
ReturnBlock.getBlock()->use_empty()3.22k
) {
511
1.45k
    Builder.ClearInsertionPoint();
512
1.45k
    ReturnBlock.getBlock()->eraseFromParent();
513
1.45k
  }
514
312k
  if (ReturnValue.isValid()) {
515
151k
    auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
516
151k
    if (RetAlloca && 
RetAlloca->use_empty()148k
) {
517
134k
      RetAlloca->eraseFromParent();
518
134k
      ReturnValue = Address::invalid();
519
134k
    }
520
151k
  }
521
312k
}
522
523
/// ShouldInstrumentFunction - Return true if the current function should be
524
/// instrumented with __cyg_profile_func_* calls
525
624k
bool CodeGenFunction::ShouldInstrumentFunction() {
526
624k
  if (!CGM.getCodeGenOpts().InstrumentFunctions &&
527
624k
      
!CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining624k
&&
528
624k
      
!CGM.getCodeGenOpts().InstrumentFunctionEntryBare624k
)
529
624k
    return false;
530
40
  if (!CurFuncDecl || 
CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()36
)
531
18
    return false;
532
22
  return true;
533
40
}
534
535
312k
bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
536
312k
  if (!CurFuncDecl)
537
15.4k
    return false;
538
296k
  return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
539
312k
}
540
541
/// ShouldXRayInstrument - Return true if the current function should be
542
/// instrumented with XRay nop sleds.
543
624k
bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
544
624k
  return CGM.getCodeGenOpts().XRayInstrumentFunctions;
545
624k
}
546
547
/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
548
/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
549
2
bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
550
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
551
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
552
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
553
1
              XRayInstrKind::Custom);
554
2
}
555
556
2
bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
557
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
558
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
559
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
560
1
              XRayInstrKind::Typed);
561
2
}
562
563
llvm::Constant *
564
CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
565
111
                                            llvm::Constant *Addr) {
566
  // Addresses stored in prologue data can't require run-time fixups and must
567
  // be PC-relative. Run-time fixups are undesirable because they necessitate
568
  // writable text segments, which are unsafe. And absolute addresses are
569
  // undesirable because they break PIE mode.
570
571
  // Add a layer of indirection through a private global. Taking its address
572
  // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
573
111
  auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
574
111
                                      /*isConstant=*/true,
575
111
                                      llvm::GlobalValue::PrivateLinkage, Addr);
576
577
  // Create a PC-relative address.
578
111
  auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
579
111
  auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
580
111
  auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
581
111
  return (IntPtrTy == Int32Ty)
582
111
             ? 
PCRelAsInt70
583
111
             : 
llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty)41
;
584
111
}
585
586
llvm::Value *
587
CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
588
8
                                          llvm::Value *EncodedAddr) {
589
  // Reconstruct the address of the global.
590
8
  auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
591
8
  auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
592
8
  auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
593
8
  auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
594
595
  // Load the original pointer through the global.
596
8
  return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
597
8
                            "decoded_addr");
598
8
}
599
600
void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
601
                                               llvm::Function *Fn)
602
1.44k
{
603
1.44k
  if (!FD->hasAttr<OpenCLKernelAttr>())
604
1.07k
    return;
605
606
370
  llvm::LLVMContext &Context = getLLVMContext();
607
608
370
  CGM.GenOpenCLArgMetadata(Fn, FD, this);
609
610
370
  if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
611
2
    QualType HintQTy = A->getTypeHint();
612
2
    const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
613
2
    bool IsSignedInteger =
614
2
        HintQTy->isSignedIntegerType() ||
615
2
        
(1
HintEltQTy1
&&
HintEltQTy->getElementType()->isSignedIntegerType()1
);
616
2
    llvm::Metadata *AttrMDArgs[] = {
617
2
        llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
618
2
            CGM.getTypes().ConvertType(A->getTypeHint()))),
619
2
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
620
2
            llvm::IntegerType::get(Context, 32),
621
2
            llvm::APInt(32, (uint64_t)(IsSignedInteger ? 
11
:
01
))))};
622
2
    Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
623
2
  }
624
625
370
  if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
626
1
    llvm::Metadata *AttrMDArgs[] = {
627
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
628
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
629
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
630
1
    Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
631
1
  }
632
633
370
  if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
634
7
    llvm::Metadata *AttrMDArgs[] = {
635
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
636
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
637
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
638
7
    Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
639
7
  }
640
641
370
  if (const OpenCLIntelReqdSubGroupSizeAttr *A =
642
370
          FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
643
1
    llvm::Metadata *AttrMDArgs[] = {
644
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
645
1
    Fn->setMetadata("intel_reqd_sub_group_size",
646
1
                    llvm::MDNode::get(Context, AttrMDArgs));
647
1
  }
648
370
}
649
650
/// Determine whether the function F ends with a return stmt.
651
160k
static bool endsWithReturn(const Decl* F) {
652
160k
  const Stmt *Body = nullptr;
653
160k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
654
119k
    Body = FD->getBody();
655
41.1k
  else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
656
1.25k
    Body = OMD->getBody();
657
658
160k
  if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
659
120k
    auto LastStmt = CS->body_rbegin();
660
120k
    if (LastStmt != CS->body_rend())
661
73.7k
      return isa<ReturnStmt>(*LastStmt);
662
120k
  }
663
86.8k
  return false;
664
160k
}
665
666
336
void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
667
336
  if (SanOpts.has(SanitizerKind::Thread)) {
668
4
    Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
669
4
    Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
670
4
  }
671
336
}
672
673
/// Check if the return value of this function requires sanitization.
674
465k
bool CodeGenFunction::requiresReturnValueCheck() const {
675
465k
  return requiresReturnValueNullabilityCheck() ||
676
465k
         
(465k
SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)465k
&&
CurCodeDecl112
&&
677
465k
          
CurCodeDecl->getAttr<ReturnsNonNullAttr>()112
);
678
465k
}
679
680
35
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
681
35
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
682
35
  if (!MD || 
!MD->getDeclName().getAsIdentifierInfo()3
||
683
35
      
!MD->getDeclName().getAsIdentifierInfo()->isStr("allocate")3
||
684
35
      
(2
MD->getNumParams() != 12
&&
MD->getNumParams() != 21
))
685
33
    return false;
686
687
2
  if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
688
0
    return false;
689
690
2
  if (MD->getNumParams() == 2) {
691
1
    auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
692
1
    if (!PT || !PT->isVoidPointerType() ||
693
1
        !PT->getPointeeType().isConstQualified())
694
0
      return false;
695
1
  }
696
697
2
  return true;
698
2
}
699
700
/// Return the UBSan prologue signature for \p FD if one is available.
701
static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
702
204
                                            const FunctionDecl *FD) {
703
204
  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
704
99
    if (!MD->isStatic())
705
93
      return nullptr;
706
111
  return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
707
204
}
708
709
void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
710
                                    llvm::Function *Fn,
711
                                    const CGFunctionInfo &FnInfo,
712
                                    const FunctionArgList &Args,
713
                                    SourceLocation Loc,
714
312k
                                    SourceLocation StartLoc) {
715
312k
  assert(!CurFn &&
716
312k
         "Do not use a CodeGenFunction object for more than one function");
717
718
0
  const Decl *D = GD.getDecl();
719
720
312k
  DidCallStackSave = false;
721
312k
  CurCodeDecl = D;
722
312k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
723
312k
  if (FD && 
FD->usesSEHTry()268k
)
724
109
    CurSEHParent = FD;
725
312k
  CurFuncDecl = (D ? 
D->getNonClosureContext()303k
:
nullptr8.94k
);
726
312k
  FnRetTy = RetTy;
727
312k
  CurFn = Fn;
728
312k
  CurFnInfo = &FnInfo;
729
312k
  assert(CurFn->isDeclaration() && "Function already has body?");
730
731
  // If this function is ignored for any of the enabled sanitizers,
732
  // disable the sanitizer for the function.
733
312k
  do {
734
312k
#define SANITIZER(NAME, ID)                                                    \
735
831k
  if (
SanOpts.empty()523k
) \
736
831k
    
break308k
; \
737
831k
  
if (214k
SanOpts.has(SanitizerKind::ID)214k
) \
738
214k
    
if (7.25k
CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)7.25k
) \
739
7.25k
      
SanOpts.set(SanitizerKind::ID, false)55
;
740
741
312k
#include "clang/Basic/Sanitizers.def"
742
214k
#undef SANITIZER
743
214k
  } while (
false3.89k
);
744
745
312k
  if (D) {
746
303k
    bool NoSanitizeCoverage = false;
747
748
303k
    for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
749
      // Apply the no_sanitize* attributes to SanOpts.
750
1.16k
      SanitizerMask mask = Attr->getMask();
751
1.16k
      SanOpts.Mask &= ~mask;
752
1.16k
      if (mask & SanitizerKind::Address)
753
65
        SanOpts.set(SanitizerKind::KernelAddress, false);
754
1.16k
      if (mask & SanitizerKind::KernelAddress)
755
5
        SanOpts.set(SanitizerKind::Address, false);
756
1.16k
      if (mask & SanitizerKind::HWAddress)
757
5
        SanOpts.set(SanitizerKind::KernelHWAddress, false);
758
1.16k
      if (mask & SanitizerKind::KernelHWAddress)
759
5
        SanOpts.set(SanitizerKind::HWAddress, false);
760
761
      // SanitizeCoverage is not handled by SanOpts.
762
1.16k
      if (Attr->hasCoverage())
763
24
        NoSanitizeCoverage = true;
764
1.16k
    }
765
766
303k
    if (NoSanitizeCoverage && 
CGM.getCodeGenOpts().hasSanitizeCoverage()24
)
767
24
      Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
768
303k
  }
769
770
  // Apply sanitizer attributes to the function.
771
312k
  if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
772
511
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
773
312k
  if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
774
38
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
775
312k
  if (SanOpts.has(SanitizerKind::MemTag))
776
19
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
777
312k
  if (SanOpts.has(SanitizerKind::Thread))
778
68
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
779
312k
  if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
780
378
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
781
312k
  if (SanOpts.has(SanitizerKind::SafeStack))
782
18
    Fn->addFnAttr(llvm::Attribute::SafeStack);
783
312k
  if (SanOpts.has(SanitizerKind::ShadowCallStack))
784
3
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
785
786
  // Apply fuzzing attribute to the function.
787
312k
  if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
788
2
    Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
789
790
  // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
791
  // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
792
312k
  if (SanOpts.has(SanitizerKind::Thread)) {
793
68
    if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
794
3
      IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
795
3
      if (OMD->getMethodFamily() == OMF_dealloc ||
796
3
          
OMD->getMethodFamily() == OMF_initialize2
||
797
3
          
(1
OMD->getSelector().isUnarySelector()1
&&
II->isStr(".cxx_destruct")1
)) {
798
3
        markAsIgnoreThreadCheckingAtRuntime(Fn);
799
3
      }
800
3
    }
801
68
  }
802
803
  // Ignore unrelated casts in STL allocate() since the allocator must cast
804
  // from void* to T* before object initialization completes. Don't match on the
805
  // namespace because not all allocators are in std::
806
312k
  if (D && 
SanOpts.has(SanitizerKind::CFIUnrelatedCast)303k
) {
807
35
    if (matchesStlAllocatorFn(D, getContext()))
808
2
      SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
809
35
  }
810
811
  // Ignore null checks in coroutine functions since the coroutines passes
812
  // are not aware of how to move the extra UBSan instructions across the split
813
  // coroutine boundaries.
814
312k
  if (D && 
SanOpts.has(SanitizerKind::Null)303k
)
815
249
    if (FD && FD->getBody() &&
816
249
        FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
817
1
      SanOpts.Mask &= ~SanitizerKind::Null;
818
819
  // Apply xray attributes to the function (as a string, for now)
820
312k
  bool AlwaysXRayAttr = false;
821
312k
  if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
822
86
    if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
823
86
            XRayInstrKind::FunctionEntry) ||
824
86
        CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
825
82
            XRayInstrKind::FunctionExit)) {
826
82
      if (XRayAttr->alwaysXRayInstrument() && 
ShouldXRayInstrumentFunction()45
) {
827
38
        Fn->addFnAttr("function-instrument", "xray-always");
828
38
        AlwaysXRayAttr = true;
829
38
      }
830
82
      if (XRayAttr->neverXRayInstrument())
831
37
        Fn->addFnAttr("function-instrument", "xray-never");
832
82
      if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
833
1
        if (ShouldXRayInstrumentFunction())
834
1
          Fn->addFnAttr("xray-log-args",
835
1
                        llvm::utostr(LogArgs->getArgumentCount()));
836
82
    }
837
312k
  } else {
838
312k
    if (ShouldXRayInstrumentFunction() && 
!CGM.imbueXRayAttrs(Fn, Loc)31
)
839
19
      Fn->addFnAttr(
840
19
          "xray-instruction-threshold",
841
19
          llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
842
312k
  }
843
844
312k
  if (ShouldXRayInstrumentFunction()) {
845
103
    if (CGM.getCodeGenOpts().XRayIgnoreLoops)
846
1
      Fn->addFnAttr("xray-ignore-loops");
847
848
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
849
103
            XRayInstrKind::FunctionExit))
850
6
      Fn->addFnAttr("xray-skip-exit");
851
852
103
    if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
853
103
            XRayInstrKind::FunctionEntry))
854
6
      Fn->addFnAttr("xray-skip-entry");
855
856
103
    auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
857
103
    if (FuncGroups > 1) {
858
15
      auto FuncName = llvm::makeArrayRef<uint8_t>(
859
15
          CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
860
15
      auto Group = crc32(FuncName) % FuncGroups;
861
15
      if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
862
15
          
!AlwaysXRayAttr10
)
863
8
        Fn->addFnAttr("function-instrument", "xray-never");
864
15
    }
865
103
  }
866
867
312k
  if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
868
475
    if (CGM.isProfileInstrExcluded(Fn, Loc))
869
4
      Fn->addFnAttr(llvm::Attribute::NoProfile);
870
871
312k
  unsigned Count, Offset;
872
312k
  if (const auto *Attr =
873
312k
          D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
874
14
    Count = Attr->getCount();
875
14
    Offset = Attr->getOffset();
876
312k
  } else {
877
312k
    Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
878
312k
    Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
879
312k
  }
880
312k
  if (Count && 
Offset <= Count11
) {
881
11
    Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
882
11
    if (Offset)
883
4
      Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
884
11
  }
885
886
  // Add no-jump-tables value.
887
312k
  if (CGM.getCodeGenOpts().NoUseJumpTables)
888
1
    Fn->addFnAttr("no-jump-tables", "true");
889
890
  // Add no-inline-line-tables value.
891
312k
  if (CGM.getCodeGenOpts().NoInlineLineTables)
892
4
    Fn->addFnAttr("no-inline-line-tables");
893
894
  // Add profile-sample-accurate value.
895
312k
  if (CGM.getCodeGenOpts().ProfileSampleAccurate)
896
2
    Fn->addFnAttr("profile-sample-accurate");
897
898
312k
  if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
899
23
    Fn->addFnAttr("use-sample-profile");
900
901
312k
  if (D && 
D->hasAttr<CFICanonicalJumpTableAttr>()303k
)
902
2
    Fn->addFnAttr("cfi-canonical-jump-table");
903
904
312k
  if (D && 
D->hasAttr<NoProfileFunctionAttr>()303k
)
905
4
    Fn->addFnAttr(llvm::Attribute::NoProfile);
906
907
312k
  if (FD && 
getLangOpts().OpenCL268k
) {
908
    // Add metadata for a kernel function.
909
1.44k
    EmitOpenCLKernelMetadata(FD, Fn);
910
1.44k
  }
911
912
  // If we are checking function types, emit a function type signature as
913
  // prologue data.
914
312k
  if (FD && 
getLangOpts().CPlusPlus268k
&&
SanOpts.has(SanitizerKind::Function)188k
) {
915
204
    if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
916
      // Remove any (C++17) exception specifications, to allow calling e.g. a
917
      // noexcept function through a non-noexcept pointer.
918
111
      auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
919
111
          FD->getType(), EST_None);
920
111
      llvm::Constant *FTRTTIConst =
921
111
          CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
922
111
      llvm::Constant *FTRTTIConstEncoded =
923
111
          EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
924
111
      llvm::Constant *PrologueStructElems[] = {PrologueSig, FTRTTIConstEncoded};
925
111
      llvm::Constant *PrologueStructConst =
926
111
          llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
927
111
      Fn->setPrologueData(PrologueStructConst);
928
111
    }
929
204
  }
930
931
  // If we're checking nullability, we need to know whether we can check the
932
  // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
933
312k
  if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
934
60
    auto Nullability = FnRetTy->getNullability(getContext());
935
60
    if (Nullability && 
*Nullability == NullabilityKind::NonNull17
) {
936
15
      if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
937
15
            
CurCodeDecl1
&&
CurCodeDecl->getAttr<ReturnsNonNullAttr>()1
))
938
14
        RetValNullabilityPrecondition =
939
14
            llvm::ConstantInt::getTrue(getLLVMContext());
940
15
    }
941
60
  }
942
943
  // If we're in C++ mode and the function name is "main", it is guaranteed
944
  // to be norecurse by the standard (3.6.1.3 "The function main shall not be
945
  // used within a program").
946
  //
947
  // OpenCL C 2.0 v2.2-11 s6.9.i:
948
  //     Recursion is not supported.
949
  //
950
  // SYCL v1.2.1 s3.10:
951
  //     kernels cannot include RTTI information, exception classes,
952
  //     recursive code, virtual functions or make use of C++ libraries that
953
  //     are not compiled for the device.
954
312k
  if (FD && 
(268k
(268k
getLangOpts().CPlusPlus268k
&&
FD->isMain()188k
) ||
955
268k
             
getLangOpts().OpenCL264k
||
getLangOpts().SYCLIsDevice262k
||
956
268k
             
(262k
getLangOpts().CUDA262k
&&
FD->hasAttr<CUDAGlobalAttr>()501
)))
957
5.55k
    Fn->addFnAttr(llvm::Attribute::NoRecurse);
958
959
312k
  llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
960
312k
  llvm::fp::ExceptionBehavior FPExceptionBehavior =
961
312k
      ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());
962
312k
  Builder.setDefaultConstrainedRounding(RM);
963
312k
  Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
964
312k
  if ((FD && 
(268k
FD->UsesFPIntrin()268k
||
FD->hasAttr<StrictFPAttr>()266k
)) ||
965
312k
      
(310k
!FD310k
&&
(43.9k
FPExceptionBehavior != llvm::fp::ebIgnore43.9k
||
966
43.9k
               
RM != llvm::RoundingMode::NearestTiesToEven43.9k
))) {
967
1.33k
    Builder.setIsFPConstrained(true);
968
1.33k
    Fn->addFnAttr(llvm::Attribute::StrictFP);
969
1.33k
  }
970
971
  // If a custom alignment is used, force realigning to this alignment on
972
  // any main function which certainly will need it.
973
312k
  if (FD && 
(268k
(268k
FD->isMain()268k
||
FD->isMSVCRTEntryPoint()262k
) &&
974
268k
             
CGM.getCodeGenOpts().StackAlignment5.54k
))
975
1
    Fn->addFnAttr("stackrealign");
976
977
312k
  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
978
979
  // Create a marker to make it easy to insert allocas into the entryblock
980
  // later.  Don't create this with the builder, because we don't want it
981
  // folded.
982
312k
  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
983
312k
  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
984
985
312k
  ReturnBlock = getJumpDestInCurrentScope("return");
986
987
312k
  Builder.SetInsertPoint(EntryBB);
988
989
  // If we're checking the return value, allocate space for a pointer to a
990
  // precise source location of the checked return statement.
991
312k
  if (requiresReturnValueCheck()) {
992
19
    ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
993
19
    Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
994
19
                        ReturnLocation);
995
19
  }
996
997
  // Emit subprogram debug descriptor.
998
312k
  if (CGDebugInfo *DI = getDebugInfo()) {
999
    // Reconstruct the type from the argument list so that implicit parameters,
1000
    // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
1001
    // convention.
1002
103k
    DI->emitFunctionStart(GD, Loc, StartLoc,
1003
103k
                          DI->getFunctionType(FD, RetTy, Args), CurFn,
1004
103k
                          CurFuncIsThunk);
1005
103k
  }
1006
1007
312k
  if (ShouldInstrumentFunction()) {
1008
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
1009
7
      CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
1010
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
1011
2
      CurFn->addFnAttr("instrument-function-entry-inlined",
1012
2
                       "__cyg_profile_func_enter");
1013
11
    if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1014
2
      CurFn->addFnAttr("instrument-function-entry-inlined",
1015
2
                       "__cyg_profile_func_enter_bare");
1016
11
  }
1017
1018
  // Since emitting the mcount call here impacts optimizations such as function
1019
  // inlining, we just add an attribute to insert a mcount call in backend.
1020
  // The attribute "counting-function" is set to mcount function name which is
1021
  // architecture dependent.
1022
312k
  if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1023
    // Calls to fentry/mcount should not be generated if function has
1024
    // the no_instrument_function attribute.
1025
147
    if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1026
117
      if (CGM.getCodeGenOpts().CallFEntry)
1027
4
        Fn->addFnAttr("fentry-call", "true");
1028
113
      else {
1029
113
        Fn->addFnAttr("instrument-function-entry-inlined",
1030
113
                      getTarget().getMCountName());
1031
113
      }
1032
117
      if (CGM.getCodeGenOpts().MNopMCount) {
1033
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1034
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1035
1
            << "-mnop-mcount" << "-mfentry";
1036
2
        Fn->addFnAttr("mnop-mcount");
1037
2
      }
1038
1039
117
      if (CGM.getCodeGenOpts().RecordMCount) {
1040
2
        if (!CGM.getCodeGenOpts().CallFEntry)
1041
1
          CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1042
1
            << "-mrecord-mcount" << "-mfentry";
1043
2
        Fn->addFnAttr("mrecord-mcount");
1044
2
      }
1045
117
    }
1046
147
  }
1047
1048
312k
  if (CGM.getCodeGenOpts().PackedStack) {
1049
2
    if (getContext().getTargetInfo().getTriple().getArch() !=
1050
2
        llvm::Triple::systemz)
1051
1
      CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1052
1
        << "-mpacked-stack";
1053
2
    Fn->addFnAttr("packed-stack");
1054
2
  }
1055
1056
312k
  if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
1057
312k
      
!CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc)33
)
1058
28
    Fn->addFnAttr("warn-stack-size",
1059
28
                  std::to_string(CGM.getCodeGenOpts().WarnStackSize));
1060
1061
312k
  if (RetTy->isVoidType()) {
1062
    // Void type; nothing to return.
1063
160k
    ReturnValue = Address::invalid();
1064
1065
    // Count the implicit return.
1066
160k
    if (!endsWithReturn(D))
1067
157k
      ++NumReturnExprs;
1068
160k
  } else 
if (151k
CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect151k
) {
1069
    // Indirect return; emit returned value directly into sret slot.
1070
    // This reduces code size, and affects correctness in C++.
1071
2.88k
    auto AI = CurFn->arg_begin();
1072
2.88k
    if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1073
54
      ++AI;
1074
2.88k
    ReturnValue = Address(&*AI, ConvertType(RetTy),
1075
2.88k
                          CurFnInfo->getReturnInfo().getIndirectAlign());
1076
2.88k
    if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1077
1.24k
      ReturnValuePointer =
1078
1.24k
          CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
1079
1.24k
      Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
1080
1.24k
                              ReturnValue.getPointer(), Int8PtrTy),
1081
1.24k
                          ReturnValuePointer);
1082
1.24k
    }
1083
148k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1084
148k
             
!hasScalarEvaluationKind(CurFnInfo->getReturnType())5
) {
1085
    // Load the sret pointer from the argument struct and return into that.
1086
5
    unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1087
5
    llvm::Function::arg_iterator EI = CurFn->arg_end();
1088
5
    --EI;
1089
5
    llvm::Value *Addr = Builder.CreateStructGEP(
1090
5
        EI->getType()->getPointerElementType(), &*EI, Idx);
1091
5
    llvm::Type *Ty =
1092
5
        cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1093
5
    ReturnValuePointer = Address(Addr, getPointerAlign());
1094
5
    Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1095
5
    ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
1096
148k
  } else {
1097
148k
    ReturnValue = CreateIRTemp(RetTy, "retval");
1098
1099
    // Tell the epilog emitter to autorelease the result.  We do this
1100
    // now so that various specialized functions can suppress it
1101
    // during their IR-generation.
1102
148k
    if (getLangOpts().ObjCAutoRefCount &&
1103
148k
        
!CurFnInfo->isReturnsRetained()423
&&
1104
148k
        
RetTy->isObjCRetainableType()388
)
1105
159
      AutoreleaseResult = true;
1106
148k
  }
1107
1108
312k
  EmitStartEHSpec(CurCodeDecl);
1109
1110
312k
  PrologueCleanupDepth = EHStack.stable_begin();
1111
1112
  // Emit OpenMP specific initialization of the device functions.
1113
312k
  if (getLangOpts().OpenMP && 
CurCodeDecl70.1k
)
1114
63.7k
    CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1115
1116
312k
  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1117
1118
312k
  if (D && 
isa<CXXMethodDecl>(D)303k
&&
cast<CXXMethodDecl>(D)->isInstance()111k
) {
1119
104k
    CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1120
104k
    const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1121
104k
    if (MD->getParent()->isLambda() &&
1122
104k
        
MD->getOverloadedOperator() == OO_Call1.82k
) {
1123
      // We're in a lambda; figure out the captures.
1124
1.64k
      MD->getParent()->getCaptureFields(LambdaCaptureFields,
1125
1.64k
                                        LambdaThisCaptureField);
1126
1.64k
      if (LambdaThisCaptureField) {
1127
        // If the lambda captures the object referred to by '*this' - either by
1128
        // value or by reference, make sure CXXThisValue points to the correct
1129
        // object.
1130
1131
        // Get the lvalue for the field (which is a copy of the enclosing object
1132
        // or contains the address of the enclosing object).
1133
79
        LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1134
79
        if (!LambdaThisCaptureField->getType()->isPointerType()) {
1135
          // If the enclosing object was captured by value, just use its address.
1136
2
          CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1137
77
        } else {
1138
          // Load the lvalue pointed to by the field, since '*this' was captured
1139
          // by reference.
1140
77
          CXXThisValue =
1141
77
              EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1142
77
        }
1143
79
      }
1144
2.69k
      for (auto *FD : MD->getParent()->fields()) {
1145
2.69k
        if (FD->hasCapturedVLAType()) {
1146
24
          auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1147
24
                                           SourceLocation()).getScalarVal();
1148
24
          auto VAT = FD->getCapturedVLAType();
1149
24
          VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1150
24
        }
1151
2.69k
      }
1152
103k
    } else {
1153
      // Not in a lambda; just use 'this' from the method.
1154
      // FIXME: Should we generate a new load for each use of 'this'?  The
1155
      // fast register allocator would be happier...
1156
103k
      CXXThisValue = CXXABIThisValue;
1157
103k
    }
1158
1159
    // Check the 'this' pointer once per function, if it's available.
1160
104k
    if (CXXABIThisValue) {
1161
104k
      SanitizerSet SkippedChecks;
1162
104k
      SkippedChecks.set(SanitizerKind::ObjectSize, true);
1163
104k
      QualType ThisTy = MD->getThisType();
1164
1165
      // If this is the call operator of a lambda with no capture-default, it
1166
      // may have a static invoker function, which may call this operator with
1167
      // a null 'this' pointer.
1168
104k
      if (isLambdaCallOperator(MD) &&
1169
104k
          
MD->getParent()->getLambdaCaptureDefault() == LCD_None1.64k
)
1170
364
        SkippedChecks.set(SanitizerKind::Null, true);
1171
1172
104k
      EmitTypeCheck(
1173
104k
          isa<CXXConstructorDecl>(MD) ? 
TCK_ConstructorCall40.8k
:
TCK_MemberCall64.0k
,
1174
104k
          Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1175
104k
    }
1176
104k
  }
1177
1178
  // If any of the arguments have a variably modified type, make sure to
1179
  // emit the type size.
1180
312k
  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1181
833k
       i != e; 
++i520k
) {
1182
520k
    const VarDecl *VD = *i;
1183
1184
    // Dig out the type as written from ParmVarDecls; it's unclear whether
1185
    // the standard (C99 6.9.1p10) requires this, but we're following the
1186
    // precedent set by gcc.
1187
520k
    QualType Ty;
1188
520k
    if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1189
327k
      Ty = PVD->getOriginalType();
1190
193k
    else
1191
193k
      Ty = VD->getType();
1192
1193
520k
    if (Ty->isVariablyModifiedType())
1194
137
      EmitVariablyModifiedType(Ty);
1195
520k
  }
1196
  // Emit a location at the end of the prologue.
1197
312k
  if (CGDebugInfo *DI = getDebugInfo())
1198
103k
    DI->EmitLocation(Builder, StartLoc);
1199
1200
  // TODO: Do we need to handle this in two places like we do with
1201
  // target-features/target-cpu?
1202
312k
  if (CurFuncDecl)
1203
296k
    if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1204
8.05k
      LargestVectorWidth = VecWidth->getVectorWidth();
1205
312k
}
1206
1207
209k
void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1208
209k
  incrementProfileCounter(Body);
1209
209k
  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1210
209k
    EmitCompoundStmtWithoutScope(*S);
1211
124
  else
1212
124
    EmitStmt(Body);
1213
1214
  // This is checked after emitting the function body so we know if there
1215
  // are any permitted infinite loops.
1216
209k
  if (checkIfFunctionMustProgress())
1217
128k
    CurFn->addFnAttr(llvm::Attribute::MustProgress);
1218
209k
}
1219
1220
/// When instrumenting to collect profile data, the counts for some blocks
1221
/// such as switch cases need to not include the fall-through counts, so
1222
/// emit a branch around the instrumentation code. When not instrumenting,
1223
/// this just calls EmitBlock().
1224
void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1225
1.90k
                                               const Stmt *S) {
1226
1.90k
  llvm::BasicBlock *SkipCountBB = nullptr;
1227
1.90k
  if (HaveInsertPoint() && 
CGM.getCodeGenOpts().hasProfileClangInstr()816
) {
1228
    // When instrumenting for profiling, the fallthrough to certain
1229
    // statements needs to skip over the instrumentation code so that we
1230
    // get an accurate count.
1231
23
    SkipCountBB = createBasicBlock("skipcount");
1232
23
    EmitBranch(SkipCountBB);
1233
23
  }
1234
1.90k
  EmitBlock(BB);
1235
1.90k
  uint64_t CurrentCount = getCurrentProfileCount();
1236
1.90k
  incrementProfileCounter(S);
1237
1.90k
  setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1238
1.90k
  if (SkipCountBB)
1239
23
    EmitBlock(SkipCountBB);
1240
1.90k
}
1241
1242
/// Tries to mark the given function nounwind based on the
1243
/// non-existence of any throwing calls within it.  We believe this is
1244
/// lightweight enough to do at -O0.
1245
197k
static void TryMarkNoThrow(llvm::Function *F) {
1246
  // LLVM treats 'nounwind' on a function as part of the type, so we
1247
  // can't do this on functions that can be overwritten.
1248
197k
  if (F->isInterposable()) 
return39
;
1249
1250
197k
  for (llvm::BasicBlock &BB : *F)
1251
310k
    for (llvm::Instruction &I : BB)
1252
2.84M
      if (I.mayThrow())
1253
71.0k
        return;
1254
1255
126k
  F->setDoesNotThrow();
1256
126k
}
1257
1258
QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1259
401k
                                               FunctionArgList &Args) {
1260
401k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1261
401k
  QualType ResTy = FD->getReturnType();
1262
1263
401k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1264
401k
  if (MD && 
MD->isInstance()119k
) {
1265
104k
    if (CGM.getCXXABI().HasThisReturn(GD))
1266
1.66k
      ResTy = MD->getThisType();
1267
103k
    else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1268
216
      ResTy = CGM.getContext().VoidPtrTy;
1269
104k
    CGM.getCXXABI().buildThisParam(*this, Args);
1270
104k
  }
1271
1272
  // The base version of an inheriting constructor whose constructed base is a
1273
  // virtual base is not passed any arguments (because it doesn't actually call
1274
  // the inherited constructor).
1275
401k
  bool PassedParams = true;
1276
401k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1277
40.8k
    if (auto Inherited = CD->getInheritedConstructor())
1278
226
      PassedParams =
1279
226
          getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1280
1281
401k
  if (PassedParams) {
1282
488k
    for (auto *Param : FD->parameters()) {
1283
488k
      Args.push_back(Param);
1284
488k
      if (!Param->hasAttr<PassObjectSizeAttr>())
1285
488k
        continue;
1286
1287
88
      auto *Implicit = ImplicitParamDecl::Create(
1288
88
          getContext(), Param->getDeclContext(), Param->getLocation(),
1289
88
          /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1290
88
      SizeArguments[Param] = Implicit;
1291
88
      Args.push_back(Implicit);
1292
88
    }
1293
401k
  }
1294
1295
401k
  if (MD && 
(119k
isa<CXXConstructorDecl>(MD)119k
||
isa<CXXDestructorDecl>(MD)78.5k
))
1296
57.4k
    CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1297
1298
401k
  return ResTy;
1299
401k
}
1300
1301
void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1302
268k
                                   const CGFunctionInfo &FnInfo) {
1303
268k
  assert(Fn && "generating code for null Function");
1304
0
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1305
268k
  CurGD = GD;
1306
1307
268k
  FunctionArgList Args;
1308
268k
  QualType ResTy = BuildFunctionArgList(GD, Args);
1309
1310
268k
  if (FD->isInlineBuiltinDeclaration()) {
1311
    // When generating code for a builtin with an inline declaration, use a
1312
    // mangled name to hold the actual body, while keeping an external
1313
    // definition in case the function pointer is referenced somewhere.
1314
13
    std::string FDInlineName = (Fn->getName() + ".inline").str();
1315
13
    llvm::Module *M = Fn->getParent();
1316
13
    llvm::Function *Clone = M->getFunction(FDInlineName);
1317
13
    if (!Clone) {
1318
3
      Clone = llvm::Function::Create(Fn->getFunctionType(),
1319
3
                                     llvm::GlobalValue::InternalLinkage,
1320
3
                                     Fn->getAddressSpace(), FDInlineName, M);
1321
3
      Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1322
3
    }
1323
13
    Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1324
13
    Fn = Clone;
1325
268k
  } else {
1326
    // Detect the unusual situation where an inline version is shadowed by a
1327
    // non-inline version. In that case we should pick the external one
1328
    // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
1329
    // to detect that situation before we reach codegen, so do some late
1330
    // replacement.
1331
274k
    for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1332
268k
         
PD = PD->getPreviousDecl()6.69k
) {
1333
6.69k
      if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1334
1
        std::string FDInlineName = (Fn->getName() + ".inline").str();
1335
1
        llvm::Module *M = Fn->getParent();
1336
1
        if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1337
1
          Clone->replaceAllUsesWith(Fn);
1338
1
          Clone->eraseFromParent();
1339
1
        }
1340
1
        break;
1341
1
      }
1342
6.69k
    }
1343
268k
  }
1344
1345
  // Check if we should generate debug info for this function.
1346
268k
  if (FD->hasAttr<NoDebugAttr>()) {
1347
    // Clear non-distinct debug info that was possibly attached to the function
1348
    // due to an earlier declaration without the nodebug attribute
1349
13.6k
    Fn->setSubprogram(nullptr);
1350
    // Disable debug info indefinitely for this function
1351
13.6k
    DebugInfo = nullptr;
1352
13.6k
  }
1353
1354
  // The function might not have a body if we're generating thunks for a
1355
  // function declaration.
1356
268k
  SourceRange BodyRange;
1357
268k
  if (Stmt *Body = FD->getBody())
1358
268k
    BodyRange = Body->getSourceRange();
1359
130
  else
1360
130
    BodyRange = FD->getLocation();
1361
268k
  CurEHLocation = BodyRange.getEnd();
1362
1363
  // Use the location of the start of the function to determine where
1364
  // the function definition is located. By default use the location
1365
  // of the declaration as the location for the subprogram. A function
1366
  // may lack a declaration in the source code if it is created by code
1367
  // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1368
268k
  SourceLocation Loc = FD->getLocation();
1369
1370
  // If this is a function specialization then use the pattern body
1371
  // as the location for the function.
1372
268k
  if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1373
99.4k
    if (SpecDecl->hasBody(SpecDecl))
1374
98.6k
      Loc = SpecDecl->getLocation();
1375
1376
268k
  Stmt *Body = FD->getBody();
1377
1378
268k
  if (Body) {
1379
    // Coroutines always emit lifetime markers.
1380
268k
    if (isa<CoroutineBodyStmt>(Body))
1381
120
      ShouldEmitLifetimeMarkers = true;
1382
1383
    // Initialize helper which will detect jumps which can cause invalid
1384
    // lifetime markers.
1385
268k
    if (ShouldEmitLifetimeMarkers)
1386
40.4k
      Bypasses.Init(Body);
1387
268k
  }
1388
1389
  // Emit the standard function prologue.
1390
268k
  StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1391
1392
  // Save parameters for coroutine function.
1393
268k
  if (Body && 
isa_and_nonnull<CoroutineBodyStmt>(Body)268k
)
1394
120
    for (const auto *ParamDecl : FD->parameters())
1395
63
      FnArgs.push_back(ParamDecl);
1396
1397
  // Generate the body of the function.
1398
268k
  PGO.assignRegionCounters(GD, CurFn);
1399
268k
  if (isa<CXXDestructorDecl>(FD))
1400
16.5k
    EmitDestructorBody(Args);
1401
251k
  else if (isa<CXXConstructorDecl>(FD))
1402
40.8k
    EmitConstructorBody(Args);
1403
210k
  else if (getLangOpts().CUDA &&
1404
210k
           
!getLangOpts().CUDAIsDevice436
&&
1405
210k
           
FD->hasAttr<CUDAGlobalAttr>()188
)
1406
55
    CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1407
210k
  else if (isa<CXXMethodDecl>(FD) &&
1408
210k
           
cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()54.0k
) {
1409
    // The lambda static invoker function is special, because it forwards or
1410
    // clones the body of the function call operator (but is actually static).
1411
60
    EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1412
210k
  } else if (FD->isDefaulted() && 
isa<CXXMethodDecl>(FD)748
&&
1413
210k
             
(744
cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator()744
||
1414
744
              
cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator()213
)) {
1415
    // Implicit copy-assignment gets the same special treatment as implicit
1416
    // copy-constructors.
1417
726
    emitImplicitAssignmentOperatorBody(Args);
1418
209k
  } else if (Body) {
1419
209k
    EmitFunctionBody(Body);
1420
209k
  } else
1421
0
    llvm_unreachable("no definition for emitted function");
1422
1423
  // C++11 [stmt.return]p2:
1424
  //   Flowing off the end of a function [...] results in undefined behavior in
1425
  //   a value-returning function.
1426
  // C11 6.9.1p12:
1427
  //   If the '}' that terminates a function is reached, and the value of the
1428
  //   function call is used by the caller, the behavior is undefined.
1429
268k
  if (getLangOpts().CPlusPlus && 
!FD->hasImplicitReturnZero()188k
&&
!SawAsmBlock184k
&&
1430
268k
      
!FD->getReturnType()->isVoidType()184k
&&
Builder.GetInsertBlock()78.1k
) {
1431
187
    bool ShouldEmitUnreachable =
1432
187
        CGM.getCodeGenOpts().StrictReturn ||
1433
187
        
!CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType())21
;
1434
187
    if (SanOpts.has(SanitizerKind::Return)) {
1435
1
      SanitizerScope SanScope(this);
1436
1
      llvm::Value *IsFalse = Builder.getFalse();
1437
1
      EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1438
1
                SanitizerHandler::MissingReturn,
1439
1
                EmitCheckSourceLocation(FD->getLocation()), None);
1440
186
    } else if (ShouldEmitUnreachable) {
1441
168
      if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1442
136
        EmitTrapCall(llvm::Intrinsic::trap);
1443
168
    }
1444
187
    if (SanOpts.has(SanitizerKind::Return) || 
ShouldEmitUnreachable186
) {
1445
169
      Builder.CreateUnreachable();
1446
169
      Builder.ClearInsertionPoint();
1447
169
    }
1448
187
  }
1449
1450
  // Emit the standard function epilogue.
1451
268k
  FinishFunction(BodyRange.getEnd());
1452
1453
  // If we haven't marked the function nothrow through other means, do
1454
  // a quick pass now to see if we can.
1455
268k
  if (!CurFn->doesNotThrow())
1456
197k
    TryMarkNoThrow(CurFn);
1457
268k
}
1458
1459
/// ContainsLabel - Return true if the statement contains a label in it.  If
1460
/// this statement is not executed normally, it not containing a label means
1461
/// that we can just remove the code.
1462
65.6k
bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1463
  // Null statement, not a label!
1464
65.6k
  if (!S) 
return false102
;
1465
1466
  // If this is a label, we have to emit the code, consider something like:
1467
  // if (0) {  ...  foo:  bar(); }  goto foo;
1468
  //
1469
  // TODO: If anyone cared, we could track __label__'s, since we know that you
1470
  // can't jump to one from outside their declared region.
1471
65.5k
  if (isa<LabelStmt>(S))
1472
6
    return true;
1473
1474
  // If this is a case/default statement, and we haven't seen a switch, we have
1475
  // to emit the code.
1476
65.5k
  if (isa<SwitchCase>(S) && 
!IgnoreCaseStmts12
)
1477
0
    return true;
1478
1479
  // If this is a switch statement, we want to ignore cases below it.
1480
65.5k
  if (isa<SwitchStmt>(S))
1481
10
    IgnoreCaseStmts = true;
1482
1483
  // Scan subexpressions for verboten labels.
1484
65.5k
  for (const Stmt *SubStmt : S->children())
1485
48.8k
    if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1486
13
      return true;
1487
1488
65.4k
  return false;
1489
65.5k
}
1490
1491
/// containsBreak - Return true if the statement contains a break out of it.
1492
/// If the statement (recursively) contains a switch or loop with a break
1493
/// inside of it, this is fine.
1494
88
bool CodeGenFunction::containsBreak(const Stmt *S) {
1495
  // Null statement, not a label!
1496
88
  if (!S) 
return false0
;
1497
1498
  // If this is a switch or loop that defines its own break scope, then we can
1499
  // include it and anything inside of it.
1500
88
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1501
88
      
isa<ForStmt>(S)85
)
1502
3
    return false;
1503
1504
85
  if (isa<BreakStmt>(S))
1505
1
    return true;
1506
1507
  // Scan subexpressions for verboten breaks.
1508
84
  for (const Stmt *SubStmt : S->children())
1509
54
    if (containsBreak(SubStmt))
1510
1
      return true;
1511
1512
83
  return false;
1513
84
}
1514
1515
210
bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1516
210
  if (!S) 
return false0
;
1517
1518
  // Some statement kinds add a scope and thus never add a decl to the current
1519
  // scope. Note, this list is longer than the list of statements that might
1520
  // have an unscoped decl nested within them, but this way is conservatively
1521
  // correct even if more statement kinds are added.
1522
210
  if (isa<IfStmt>(S) || 
isa<SwitchStmt>(S)208
||
isa<WhileStmt>(S)208
||
1523
210
      
isa<DoStmt>(S)208
||
isa<ForStmt>(S)205
||
isa<CompoundStmt>(S)205
||
1524
210
      
isa<CXXForRangeStmt>(S)195
||
isa<CXXTryStmt>(S)195
||
1525
210
      
isa<ObjCForCollectionStmt>(S)195
||
isa<ObjCAtTryStmt>(S)195
)
1526
15
    return false;
1527
1528
195
  if (isa<DeclStmt>(S))
1529
7
    return true;
1530
1531
188
  for (const Stmt *SubStmt : S->children())
1532
145
    if (mightAddDeclToScope(SubStmt))
1533
2
      return true;
1534
1535
186
  return false;
1536
188
}
1537
1538
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1539
/// to a constant, or if it does but contains a label, return false.  If it
1540
/// constant folds return true and set the boolean result in Result.
1541
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1542
                                                   bool &ResultBool,
1543
159k
                                                   bool AllowLabels) {
1544
159k
  llvm::APSInt ResultInt;
1545
159k
  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1546
144k
    return false;
1547
1548
14.9k
  ResultBool = ResultInt.getBoolValue();
1549
14.9k
  return true;
1550
159k
}
1551
1552
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1553
/// to a constant, or if it does but contains a label, return false.  If it
1554
/// constant folds return true and set the folded value.
1555
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1556
                                                   llvm::APSInt &ResultInt,
1557
159k
                                                   bool AllowLabels) {
1558
  // FIXME: Rename and handle conversion of other evaluatable things
1559
  // to bool.
1560
159k
  Expr::EvalResult Result;
1561
159k
  if (!Cond->EvaluateAsInt(Result, getContext()))
1562
145k
    return false;  // Not foldable, not integer or not fully evaluatable.
1563
1564
14.9k
  llvm::APSInt Int = Result.Val.getInt();
1565
14.9k
  if (!AllowLabels && 
CodeGenFunction::ContainsLabel(Cond)14.9k
)
1566
0
    return false;  // Contains a label.
1567
1568
14.9k
  ResultInt = Int;
1569
14.9k
  return true;
1570
14.9k
}
1571
1572
/// Determine whether the given condition is an instrumentable condition
1573
/// (i.e. no "&&" or "||").
1574
672
bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1575
  // Bypass simplistic logical-NOT operator before determining whether the
1576
  // condition contains any other logical operator.
1577
672
  if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1578
9
    if (UnOp->getOpcode() == UO_LNot)
1579
8
      C = UnOp->getSubExpr();
1580
1581
672
  const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1582
672
  return (!BOp || 
!BOp->isLogicalOp()256
);
1583
672
}
1584
1585
/// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1586
/// increments a profile counter based on the semantics of the given logical
1587
/// operator opcode.  This is used to instrument branch condition coverage for
1588
/// logical operators.
1589
void CodeGenFunction::EmitBranchToCounterBlock(
1590
    const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1591
    llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1592
7.45k
    Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1593
  // If not instrumenting, just emit a branch.
1594
7.45k
  bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1595
7.45k
  if (!InstrumentRegions || 
!isInstrumentedCondition(Cond)78
)
1596
7.39k
    return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1597
1598
62
  llvm::BasicBlock *ThenBlock = nullptr;
1599
62
  llvm::BasicBlock *ElseBlock = nullptr;
1600
62
  llvm::BasicBlock *NextBlock = nullptr;
1601
1602
  // Create the block we'll use to increment the appropriate counter.
1603
62
  llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1604
1605
  // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1606
  // means we need to evaluate the condition and increment the counter on TRUE:
1607
  //
1608
  // if (Cond)
1609
  //   goto CounterIncrBlock;
1610
  // else
1611
  //   goto FalseBlock;
1612
  //
1613
  // CounterIncrBlock:
1614
  //   Counter++;
1615
  //   goto TrueBlock;
1616
1617
62
  if (LOp == BO_LAnd) {
1618
35
    ThenBlock = CounterIncrBlock;
1619
35
    ElseBlock = FalseBlock;
1620
35
    NextBlock = TrueBlock;
1621
35
  }
1622
1623
  // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1624
  // we need to evaluate the condition and increment the counter on FALSE:
1625
  //
1626
  // if (Cond)
1627
  //   goto TrueBlock;
1628
  // else
1629
  //   goto CounterIncrBlock;
1630
  //
1631
  // CounterIncrBlock:
1632
  //   Counter++;
1633
  //   goto FalseBlock;
1634
1635
27
  else if (LOp == BO_LOr) {
1636
27
    ThenBlock = TrueBlock;
1637
27
    ElseBlock = CounterIncrBlock;
1638
27
    NextBlock = FalseBlock;
1639
27
  } else {
1640
0
    llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1641
0
  }
1642
1643
  // Emit Branch based on condition.
1644
62
  EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1645
1646
  // Emit the block containing the counter increment(s).
1647
62
  EmitBlock(CounterIncrBlock);
1648
1649
  // Increment corresponding counter; if index not provided, use Cond as index.
1650
62
  incrementProfileCounter(CntrIdx ? 
CntrIdx2
:
Cond60
);
1651
1652
  // Go to the next block.
1653
62
  EmitBranch(NextBlock);
1654
62
}
1655
1656
/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1657
/// statement) to the specified blocks.  Based on the condition, this might try
1658
/// to simplify the codegen of the conditional based on the branch.
1659
/// \param LH The value of the likelihood attribute on the True branch.
1660
void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1661
                                           llvm::BasicBlock *TrueBlock,
1662
                                           llvm::BasicBlock *FalseBlock,
1663
                                           uint64_t TrueCount,
1664
159k
                                           Stmt::Likelihood LH) {
1665
159k
  Cond = Cond->IgnoreParens();
1666
1667
159k
  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1668
1669
    // Handle X && Y in a condition.
1670
70.4k
    if (CondBOp->getOpcode() == BO_LAnd) {
1671
      // If we have "1 && X", simplify the code.  "0 && X" would have constant
1672
      // folded if the case was simple enough.
1673
7.00k
      bool ConstantBool = false;
1674
7.00k
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1675
7.00k
          
ConstantBool62
) {
1676
        // br(1 && X) -> br(X).
1677
62
        incrementProfileCounter(CondBOp);
1678
62
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1679
62
                                        FalseBlock, TrueCount, LH);
1680
62
      }
1681
1682
      // If we have "X && 1", simplify the code to use an uncond branch.
1683
      // "X && 0" would have been constant folded to 0.
1684
6.94k
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1685
6.94k
          
ConstantBool29
) {
1686
        // br(X && 1) -> br(X).
1687
29
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1688
29
                                        FalseBlock, TrueCount, LH, CondBOp);
1689
29
      }
1690
1691
      // Emit the LHS as a conditional.  If the LHS conditional is false, we
1692
      // want to jump to the FalseBlock.
1693
6.91k
      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1694
      // The counter tells us how often we evaluate RHS, and all of TrueCount
1695
      // can be propagated to that branch.
1696
6.91k
      uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1697
1698
6.91k
      ConditionalEvaluation eval(*this);
1699
6.91k
      {
1700
6.91k
        ApplyDebugLocation DL(*this, Cond);
1701
        // Propagate the likelihood attribute like __builtin_expect
1702
        // __builtin_expect(X && Y, 1) -> X and Y are likely
1703
        // __builtin_expect(X && Y, 0) -> only Y is unlikely
1704
6.91k
        EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1705
6.91k
                             LH == Stmt::LH_Unlikely ? 
Stmt::LH_None1
:
LH6.91k
);
1706
6.91k
        EmitBlock(LHSTrue);
1707
6.91k
      }
1708
1709
6.91k
      incrementProfileCounter(CondBOp);
1710
6.91k
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1711
1712
      // Any temporaries created here are conditional.
1713
6.91k
      eval.begin(*this);
1714
6.91k
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1715
6.91k
                               FalseBlock, TrueCount, LH);
1716
6.91k
      eval.end(*this);
1717
1718
6.91k
      return;
1719
6.94k
    }
1720
1721
63.4k
    if (CondBOp->getOpcode() == BO_LOr) {
1722
      // If we have "0 || X", simplify the code.  "1 || X" would have constant
1723
      // folded if the case was simple enough.
1724
450
      bool ConstantBool = false;
1725
450
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1726
450
          
!ConstantBool7
) {
1727
        // br(0 || X) -> br(X).
1728
7
        incrementProfileCounter(CondBOp);
1729
7
        return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1730
7
                                        FalseBlock, TrueCount, LH);
1731
7
      }
1732
1733
      // If we have "X || 0", simplify the code to use an uncond branch.
1734
      // "X || 1" would have been constant folded to 1.
1735
443
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1736
443
          
!ConstantBool1
) {
1737
        // br(X || 0) -> br(X).
1738
1
        return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1739
1
                                        FalseBlock, TrueCount, LH, CondBOp);
1740
1
      }
1741
1742
      // Emit the LHS as a conditional.  If the LHS conditional is true, we
1743
      // want to jump to the TrueBlock.
1744
442
      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1745
      // We have the count for entry to the RHS and for the whole expression
1746
      // being true, so we can divy up True count between the short circuit and
1747
      // the RHS.
1748
442
      uint64_t LHSCount =
1749
442
          getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1750
442
      uint64_t RHSCount = TrueCount - LHSCount;
1751
1752
442
      ConditionalEvaluation eval(*this);
1753
442
      {
1754
        // Propagate the likelihood attribute like __builtin_expect
1755
        // __builtin_expect(X || Y, 1) -> only Y is likely
1756
        // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1757
442
        ApplyDebugLocation DL(*this, Cond);
1758
442
        EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1759
442
                             LH == Stmt::LH_Likely ? 
Stmt::LH_None1
:
LH441
);
1760
442
        EmitBlock(LHSFalse);
1761
442
      }
1762
1763
442
      incrementProfileCounter(CondBOp);
1764
442
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1765
1766
      // Any temporaries created here are conditional.
1767
442
      eval.begin(*this);
1768
442
      EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1769
442
                               RHSCount, LH);
1770
1771
442
      eval.end(*this);
1772
1773
442
      return;
1774
443
    }
1775
63.4k
  }
1776
1777
152k
  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1778
    // br(!x, t, f) -> br(x, f, t)
1779
1.33k
    if (CondUOp->getOpcode() == UO_LNot) {
1780
      // Negate the count.
1781
1.33k
      uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1782
      // The values of the enum are chosen to make this negation possible.
1783
1.33k
      LH = static_cast<Stmt::Likelihood>(-LH);
1784
      // Negate the condition and swap the destination blocks.
1785
1.33k
      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1786
1.33k
                                  FalseCount, LH);
1787
1.33k
    }
1788
1.33k
  }
1789
1790
150k
  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1791
    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1792
2
    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1793
2
    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1794
1795
    // The ConditionalOperator itself has no likelihood information for its
1796
    // true and false branches. This matches the behavior of __builtin_expect.
1797
2
    ConditionalEvaluation cond(*this);
1798
2
    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1799
2
                         getProfileCount(CondOp), Stmt::LH_None);
1800
1801
    // When computing PGO branch weights, we only know the overall count for
1802
    // the true block. This code is essentially doing tail duplication of the
1803
    // naive code-gen, introducing new edges for which counts are not
1804
    // available. Divide the counts proportionally between the LHS and RHS of
1805
    // the conditional operator.
1806
2
    uint64_t LHSScaledTrueCount = 0;
1807
2
    if (TrueCount) {
1808
0
      double LHSRatio =
1809
0
          getProfileCount(CondOp) / (double)getCurrentProfileCount();
1810
0
      LHSScaledTrueCount = TrueCount * LHSRatio;
1811
0
    }
1812
1813
2
    cond.begin(*this);
1814
2
    EmitBlock(LHSBlock);
1815
2
    incrementProfileCounter(CondOp);
1816
2
    {
1817
2
      ApplyDebugLocation DL(*this, Cond);
1818
2
      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1819
2
                           LHSScaledTrueCount, LH);
1820
2
    }
1821
2
    cond.end(*this);
1822
1823
2
    cond.begin(*this);
1824
2
    EmitBlock(RHSBlock);
1825
2
    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1826
2
                         TrueCount - LHSScaledTrueCount, LH);
1827
2
    cond.end(*this);
1828
1829
2
    return;
1830
2
  }
1831
1832
150k
  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1833
    // Conditional operator handling can give us a throw expression as a
1834
    // condition for a case like:
1835
    //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1836
    // Fold this to:
1837
    //   br(c, throw x, br(y, t, f))
1838
0
    EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1839
0
    return;
1840
0
  }
1841
1842
  // Emit the code with the fully general case.
1843
150k
  llvm::Value *CondV;
1844
150k
  {
1845
150k
    ApplyDebugLocation DL(*this, Cond);
1846
150k
    CondV = EvaluateExprAsBool(Cond);
1847
150k
  }
1848
1849
150k
  llvm::MDNode *Weights = nullptr;
1850
150k
  llvm::MDNode *Unpredictable = nullptr;
1851
1852
  // If the branch has a condition wrapped by __builtin_unpredictable,
1853
  // create metadata that specifies that the branch is unpredictable.
1854
  // Don't bother if not optimizing because that metadata would not be used.
1855
150k
  auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1856
150k
  if (Call && 
CGM.getCodeGenOpts().OptimizationLevel != 05.93k
) {
1857
103
    auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1858
103
    if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1859
2
      llvm::MDBuilder MDHelper(getLLVMContext());
1860
2
      Unpredictable = MDHelper.createUnpredictable();
1861
2
    }
1862
103
  }
1863
1864
  // If there is a Likelihood knowledge for the cond, lower it.
1865
  // Note that if not optimizing this won't emit anything.
1866
150k
  llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1867
150k
  if (CondV != NewCondV)
1868
40
    CondV = NewCondV;
1869
150k
  else {
1870
    // Otherwise, lower profile counts. Note that we do this even at -O0.
1871
150k
    uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1872
150k
    Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1873
150k
  }
1874
1875
150k
  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1876
150k
}
1877
1878
/// ErrorUnsupported - Print out an error that codegen doesn't support the
1879
/// specified stmt yet.
1880
1
void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1881
1
  CGM.ErrorUnsupported(S, Type);
1882
1
}
1883
1884
/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1885
/// variable-length array whose elements have a non-zero bit-pattern.
1886
///
1887
/// \param baseType the inner-most element type of the array
1888
/// \param src - a char* pointing to the bit-pattern for a single
1889
/// base element of the array
1890
/// \param sizeInChars - the total size of the VLA, in chars
1891
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1892
                               Address dest, Address src,
1893
0
                               llvm::Value *sizeInChars) {
1894
0
  CGBuilderTy &Builder = CGF.Builder;
1895
1896
0
  CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1897
0
  llvm::Value *baseSizeInChars
1898
0
    = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1899
1900
0
  Address begin =
1901
0
    Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1902
0
  llvm::Value *end = Builder.CreateInBoundsGEP(
1903
0
      begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
1904
1905
0
  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1906
0
  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1907
0
  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1908
1909
  // Make a loop over the VLA.  C99 guarantees that the VLA element
1910
  // count must be nonzero.
1911
0
  CGF.EmitBlock(loopBB);
1912
1913
0
  llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1914
0
  cur->addIncoming(begin.getPointer(), originBB);
1915
1916
0
  CharUnits curAlign =
1917
0
    dest.getAlignment().alignmentOfArrayElement(baseSize);
1918
1919
  // memcpy the individual element bit-pattern.
1920
0
  Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1921
0
                       /*volatile*/ false);
1922
1923
  // Go to the next element.
1924
0
  llvm::Value *next =
1925
0
    Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1926
1927
  // Leave if that's the end of the VLA.
1928
0
  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1929
0
  Builder.CreateCondBr(done, contBB, loopBB);
1930
0
  cur->addIncoming(next, loopBB);
1931
1932
0
  CGF.EmitBlock(contBB);
1933
0
}
1934
1935
void
1936
7.20k
CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1937
  // Ignore empty classes in C++.
1938
7.20k
  if (getLangOpts().CPlusPlus) {
1939
7.05k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1940
6.70k
      if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1941
5.98k
        return;
1942
6.70k
    }
1943
7.05k
  }
1944
1945
  // Cast the dest ptr to the appropriate i8 pointer type.
1946
1.21k
  if (DestPtr.getElementType() != Int8Ty)
1947
1.21k
    DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1948
1949
  // Get size and alignment info for this aggregate.
1950
1.21k
  CharUnits size = getContext().getTypeSizeInChars(Ty);
1951
1952
1.21k
  llvm::Value *SizeVal;
1953
1.21k
  const VariableArrayType *vla;
1954
1955
  // Don't bother emitting a zero-byte memset.
1956
1.21k
  if (size.isZero()) {
1957
    // But note that getTypeInfo returns 0 for a VLA.
1958
11
    if (const VariableArrayType *vlaType =
1959
11
          dyn_cast_or_null<VariableArrayType>(
1960
11
                                          getContext().getAsArrayType(Ty))) {
1961
8
      auto VlaSize = getVLASize(vlaType);
1962
8
      SizeVal = VlaSize.NumElts;
1963
8
      CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1964
8
      if (!eltSize.isOne())
1965
8
        SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1966
8
      vla = vlaType;
1967
8
    } else {
1968
3
      return;
1969
3
    }
1970
1.20k
  } else {
1971
1.20k
    SizeVal = CGM.getSize(size);
1972
1.20k
    vla = nullptr;
1973
1.20k
  }
1974
1975
  // If the type contains a pointer to data member we can't memset it to zero.
1976
  // Instead, create a null constant and copy it to the destination.
1977
  // TODO: there are other patterns besides zero that we can usefully memset,
1978
  // like -1, which happens to be the pattern used by member-pointers.
1979
1.21k
  if (!CGM.getTypes().isZeroInitializable(Ty)) {
1980
    // For a VLA, emit a single element, then splat that over the VLA.
1981
9
    if (vla) 
Ty = getContext().getBaseElementType(vla)0
;
1982
1983
9
    llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1984
1985
9
    llvm::GlobalVariable *NullVariable =
1986
9
      new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1987
9
                               /*isConstant=*/true,
1988
9
                               llvm::GlobalVariable::PrivateLinkage,
1989
9
                               NullConstant, Twine());
1990
9
    CharUnits NullAlign = DestPtr.getAlignment();
1991
9
    NullVariable->setAlignment(NullAlign.getAsAlign());
1992
9
    Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1993
9
                   NullAlign);
1994
1995
9
    if (vla) 
return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal)0
;
1996
1997
    // Get and call the appropriate llvm.memcpy overload.
1998
9
    Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1999
9
    return;
2000
9
  }
2001
2002
  // Otherwise, just memset the whole thing to zero.  This is legal
2003
  // because in LLVM, all default initializers (other than the ones we just
2004
  // handled above) are guaranteed to have a bit pattern of all zeros.
2005
1.20k
  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2006
1.20k
}
2007
2008
61
llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2009
  // Make sure that there is a block for the indirect goto.
2010
61
  if (!IndirectBranch)
2011
38
    GetIndirectGotoBlock();
2012
2013
61
  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2014
2015
  // Make sure the indirect branch includes all of the address-taken blocks.
2016
61
  IndirectBranch->addDestination(BB);
2017
61
  return llvm::BlockAddress::get(CurFn, BB);
2018
61
}
2019
2020
60
llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2021
  // If we already made the indirect branch for indirect goto, return its block.
2022
60
  if (IndirectBranch) 
return IndirectBranch->getParent()21
;
2023
2024
39
  CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2025
2026
  // Create the PHI node that indirect gotos will add entries to.
2027
39
  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2028
39
                                              "indirect.goto.dest");
2029
2030
  // Create the indirect branch instruction.
2031
39
  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2032
39
  return IndirectBranch->getParent();
2033
60
}
2034
2035
/// Computes the length of an array in elements, as well as the base
2036
/// element type and a properly-typed first element pointer.
2037
llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2038
                                              QualType &baseType,
2039
4.79k
                                              Address &addr) {
2040
4.79k
  const ArrayType *arrayType = origArrayType;
2041
2042
  // If it's a VLA, we have to load the stored size.  Note that
2043
  // this is the size of the VLA in bytes, not its size in elements.
2044
4.79k
  llvm::Value *numVLAElements = nullptr;
2045
4.79k
  if (isa<VariableArrayType>(arrayType)) {
2046
614
    numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2047
2048
    // Walk into all VLAs.  This doesn't require changes to addr,
2049
    // which has type T* where T is the first non-VLA element type.
2050
651
    do {
2051
651
      QualType elementType = arrayType->getElementType();
2052
651
      arrayType = getContext().getAsArrayType(elementType);
2053
2054
      // If we only have VLA components, 'addr' requires no adjustment.
2055
651
      if (!arrayType) {
2056
610
        baseType = elementType;
2057
610
        return numVLAElements;
2058
610
      }
2059
651
    } while (
isa<VariableArrayType>(arrayType)41
);
2060
2061
    // We get out here only if we find a constant array type
2062
    // inside the VLA.
2063
614
  }
2064
2065
  // We have some number of constant-length arrays, so addr should
2066
  // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2067
  // down to the first element of addr.
2068
4.18k
  SmallVector<llvm::Value*, 8> gepIndices;
2069
2070
  // GEP down to the array type.
2071
4.18k
  llvm::ConstantInt *zero = Builder.getInt32(0);
2072
4.18k
  gepIndices.push_back(zero);
2073
2074
4.18k
  uint64_t countFromCLAs = 1;
2075
4.18k
  QualType eltType;
2076
2077
4.18k
  llvm::ArrayType *llvmArrayType =
2078
4.18k
    dyn_cast<llvm::ArrayType>(addr.getElementType());
2079
8.13k
  while (llvmArrayType) {
2080
3.95k
    assert(isa<ConstantArrayType>(arrayType));
2081
0
    assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
2082
3.95k
             == llvmArrayType->getNumElements());
2083
2084
0
    gepIndices.push_back(zero);
2085
3.95k
    countFromCLAs *= llvmArrayType->getNumElements();
2086
3.95k
    eltType = arrayType->getElementType();
2087
2088
3.95k
    llvmArrayType =
2089
3.95k
      dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2090
3.95k
    arrayType = getContext().getAsArrayType(arrayType->getElementType());
2091
3.95k
    assert((!llvmArrayType || arrayType) &&
2092
3.95k
           "LLVM and Clang types are out-of-synch");
2093
3.95k
  }
2094
2095
4.18k
  if (arrayType) {
2096
    // From this point onwards, the Clang array type has been emitted
2097
    // as some other type (probably a packed struct). Compute the array
2098
    // size, and just emit the 'begin' expression as a bitcast.
2099
694
    while (arrayType) {
2100
368
      countFromCLAs *=
2101
368
          cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
2102
368
      eltType = arrayType->getElementType();
2103
368
      arrayType = getContext().getAsArrayType(eltType);
2104
368
    }
2105
2106
326
    llvm::Type *baseType = ConvertType(eltType);
2107
326
    addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
2108
3.85k
  } else {
2109
    // Create the actual GEP.
2110
3.85k
    addr = Address(Builder.CreateInBoundsGEP(
2111
3.85k
        addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
2112
3.85k
        ConvertTypeForMem(eltType),
2113
3.85k
        addr.getAlignment());
2114
3.85k
  }
2115
2116
4.18k
  baseType = eltType;
2117
2118
4.18k
  llvm::Value *numElements
2119
4.18k
    = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2120
2121
  // If we had any VLA dimensions, factor them in.
2122
4.18k
  if (numVLAElements)
2123
4
    numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2124
2125
4.18k
  return numElements;
2126
4.79k
}
2127
2128
2.16k
CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2129
2.16k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2130
2.16k
  assert(vla && "type was not a variable array type!");
2131
0
  return getVLASize(vla);
2132
2.16k
}
2133
2134
CodeGenFunction::VlaSizePair
2135
5.76k
CodeGenFunction::getVLASize(const VariableArrayType *type) {
2136
  // The number of elements so far; always size_t.
2137
5.76k
  llvm::Value *numElements = nullptr;
2138
2139
5.76k
  QualType elementType;
2140
7.30k
  do {
2141
7.30k
    elementType = type->getElementType();
2142
7.30k
    llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2143
7.30k
    assert(vlaSize && "no size for VLA!");
2144
0
    assert(vlaSize->getType() == SizeTy);
2145
2146
7.30k
    if (!numElements) {
2147
5.76k
      numElements = vlaSize;
2148
5.76k
    } else {
2149
      // It's undefined behavior if this wraps around, so mark it that way.
2150
      // FIXME: Teach -fsanitize=undefined to trap this.
2151
1.54k
      numElements = Builder.CreateNUWMul(numElements, vlaSize);
2152
1.54k
    }
2153
7.30k
  } while ((type = getContext().getAsVariableArrayType(elementType)));
2154
2155
0
  return { numElements, elementType };
2156
5.76k
}
2157
2158
CodeGenFunction::VlaSizePair
2159
3.20k
CodeGenFunction::getVLAElements1D(QualType type) {
2160
3.20k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2161
3.20k
  assert(vla && "type was not a variable array type!");
2162
0
  return getVLAElements1D(vla);
2163
3.20k
}
2164
2165
CodeGenFunction::VlaSizePair
2166
3.20k
CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2167
3.20k
  llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2168
3.20k
  assert(VlaSize && "no size for VLA!");
2169
0
  assert(VlaSize->getType() == SizeTy);
2170
0
  return { VlaSize, Vla->getElementType() };
2171
3.20k
}
2172
2173
2.86k
void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2174
2.86k
  assert(type->isVariablyModifiedType() &&
2175
2.86k
         "Must pass variably modified type to EmitVLASizes!");
2176
2177
0
  EnsureInsertPoint();
2178
2179
  // We're going to walk down into the type and look for VLA
2180
  // expressions.
2181
4.07k
  do {
2182
4.07k
    assert(type->isVariablyModifiedType());
2183
2184
0
    const Type *ty = type.getTypePtr();
2185
4.07k
    switch (ty->getTypeClass()) {
2186
2187
0
#define TYPE(Class, Base)
2188
0
#define ABSTRACT_TYPE(Class, Base)
2189
0
#define NON_CANONICAL_TYPE(Class, Base)
2190
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2191
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2192
0
#include "clang/AST/TypeNodes.inc"
2193
0
      llvm_unreachable("unexpected dependent type!");
2194
2195
    // These types are never variably-modified.
2196
0
    case Type::Builtin:
2197
0
    case Type::Complex:
2198
0
    case Type::Vector:
2199
0
    case Type::ExtVector:
2200
0
    case Type::ConstantMatrix:
2201
0
    case Type::Record:
2202
0
    case Type::Enum:
2203
0
    case Type::Elaborated:
2204
0
    case Type::Using:
2205
0
    case Type::TemplateSpecialization:
2206
0
    case Type::ObjCTypeParam:
2207
0
    case Type::ObjCObject:
2208
0
    case Type::ObjCInterface:
2209
0
    case Type::ObjCObjectPointer:
2210
0
    case Type::BitInt:
2211
0
      llvm_unreachable("type class is never variably-modified!");
2212
2213
0
    case Type::Adjusted:
2214
0
      type = cast<AdjustedType>(ty)->getAdjustedType();
2215
0
      break;
2216
2217
70
    case Type::Decayed:
2218
70
      type = cast<DecayedType>(ty)->getPointeeType();
2219
70
      break;
2220
2221
91
    case Type::Pointer:
2222
91
      type = cast<PointerType>(ty)->getPointeeType();
2223
91
      break;
2224
2225
0
    case Type::BlockPointer:
2226
0
      type = cast<BlockPointerType>(ty)->getPointeeType();
2227
0
      break;
2228
2229
3
    case Type::LValueReference:
2230
3
    case Type::RValueReference:
2231
3
      type = cast<ReferenceType>(ty)->getPointeeType();
2232
3
      break;
2233
2234
0
    case Type::MemberPointer:
2235
0
      type = cast<MemberPointerType>(ty)->getPointeeType();
2236
0
      break;
2237
2238
2
    case Type::ConstantArray:
2239
12
    case Type::IncompleteArray:
2240
      // Losing element qualification here is fine.
2241
12
      type = cast<ArrayType>(ty)->getElementType();
2242
12
      break;
2243
2244
3.80k
    case Type::VariableArray: {
2245
      // Losing element qualification here is fine.
2246
3.80k
      const VariableArrayType *vat = cast<VariableArrayType>(ty);
2247
2248
      // Unknown size indication requires no size computation.
2249
      // Otherwise, evaluate and record it.
2250
3.80k
      if (const Expr *sizeExpr = vat->getSizeExpr()) {
2251
        // It's possible that we might have emitted this already,
2252
        // e.g. with a typedef and a pointer to it.
2253
3.80k
        llvm::Value *&entry = VLASizeMap[sizeExpr];
2254
3.80k
        if (!entry) {
2255
3.44k
          llvm::Value *size = EmitScalarExpr(sizeExpr);
2256
2257
          // C11 6.7.6.2p5:
2258
          //   If the size is an expression that is not an integer constant
2259
          //   expression [...] each time it is evaluated it shall have a value
2260
          //   greater than zero.
2261
3.44k
          if (SanOpts.has(SanitizerKind::VLABound)) {
2262
4
            SanitizerScope SanScope(this);
2263
4
            llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
2264
4
            clang::QualType SEType = sizeExpr->getType();
2265
4
            llvm::Value *CheckCondition =
2266
4
                SEType->isSignedIntegerType()
2267
4
                    ? 
Builder.CreateICmpSGT(size, Zero)2
2268
4
                    : 
Builder.CreateICmpUGT(size, Zero)2
;
2269
4
            llvm::Constant *StaticArgs[] = {
2270
4
                EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
2271
4
                EmitCheckTypeDescriptor(SEType)};
2272
4
            EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
2273
4
                      SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2274
4
          }
2275
2276
          // Always zexting here would be wrong if it weren't
2277
          // undefined behavior to have a negative bound.
2278
          // FIXME: What about when size's type is larger than size_t?
2279
3.44k
          entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
2280
3.44k
        }
2281
3.80k
      }
2282
3.80k
      type = vat->getElementType();
2283
3.80k
      break;
2284
2
    }
2285
2286
1
    case Type::FunctionProto:
2287
1
    case Type::FunctionNoProto:
2288
1
      type = cast<FunctionType>(ty)->getReturnType();
2289
1
      break;
2290
2291
43
    case Type::Paren:
2292
45
    case Type::TypeOf:
2293
45
    case Type::UnaryTransform:
2294
45
    case Type::Attributed:
2295
45
    case Type::SubstTemplateTypeParm:
2296
45
    case Type::MacroQualified:
2297
      // Keep walking after single level desugaring.
2298
45
      type = type.getSingleStepDesugaredType(getContext());
2299
45
      break;
2300
2301
28
    case Type::Typedef:
2302
28
    case Type::Decltype:
2303
28
    case Type::Auto:
2304
28
    case Type::DeducedTemplateSpecialization:
2305
      // Stop walking: nothing to do.
2306
28
      return;
2307
2308
14
    case Type::TypeOfExpr:
2309
      // Stop walking: emit typeof expression.
2310
14
      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2311
14
      return;
2312
2313
1
    case Type::Atomic:
2314
1
      type = cast<AtomicType>(ty)->getValueType();
2315
1
      break;
2316
2317
0
    case Type::Pipe:
2318
0
      type = cast<PipeType>(ty)->getElementType();
2319
0
      break;
2320
4.07k
    }
2321
4.07k
  } while (
type->isVariablyModifiedType()4.02k
);
2322
2.86k
}
2323
2324
1.31k
Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2325
1.31k
  if (getContext().getBuiltinVaListType()->isArrayType())
2326
521
    return EmitPointerWithAlignment(E);
2327
789
  return EmitLValue(E).getAddress(*this);
2328
1.31k
}
2329
2330
40
Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2331
40
  return EmitLValue(E).getAddress(*this);
2332
40
}
2333
2334
void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2335
6.52k
                                              const APValue &Init) {
2336
6.52k
  assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2337
6.52k
  if (CGDebugInfo *Dbg = getDebugInfo())
2338
3.97k
    if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2339
3.96k
      Dbg->EmitGlobalVariable(E->getDecl(), Init);
2340
6.52k
}
2341
2342
CodeGenFunction::PeepholeProtection
2343
1.66k
CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2344
  // At the moment, the only aggressive peephole we do in IR gen
2345
  // is trunc(zext) folding, but if we add more, we can easily
2346
  // extend this protection.
2347
2348
1.66k
  if (!rvalue.isScalar()) 
return PeepholeProtection()77
;
2349
1.58k
  llvm::Value *value = rvalue.getScalarVal();
2350
1.58k
  if (!isa<llvm::ZExtInst>(value)) 
return PeepholeProtection()1.51k
;
2351
2352
  // Just make an extra bitcast.
2353
77
  assert(HaveInsertPoint());
2354
0
  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2355
77
                                                  Builder.GetInsertBlock());
2356
2357
77
  PeepholeProtection protection;
2358
77
  protection.Inst = inst;
2359
77
  return protection;
2360
1.58k
}
2361
2362
1.66k
void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2363
1.66k
  if (!protection.Inst) 
return1.58k
;
2364
2365
  // In theory, we could try to duplicate the peepholes now, but whatever.
2366
77
  protection.Inst->eraseFromParent();
2367
77
}
2368
2369
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2370
                                              QualType Ty, SourceLocation Loc,
2371
                                              SourceLocation AssumptionLoc,
2372
                                              llvm::Value *Alignment,
2373
442
                                              llvm::Value *OffsetValue) {
2374
442
  if (Alignment->getType() != IntPtrTy)
2375
200
    Alignment =
2376
200
        Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2377
442
  if (OffsetValue && 
OffsetValue->getType() != IntPtrTy16
)
2378
5
    OffsetValue =
2379
5
        Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2380
442
  llvm::Value *TheCheck = nullptr;
2381
442
  if (SanOpts.has(SanitizerKind::Alignment)) {
2382
33
    llvm::Value *PtrIntValue =
2383
33
        Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2384
2385
33
    if (OffsetValue) {
2386
9
      bool IsOffsetZero = false;
2387
9
      if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2388
6
        IsOffsetZero = CI->isZero();
2389
2390
9
      if (!IsOffsetZero)
2391
9
        PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2392
9
    }
2393
2394
33
    llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2395
33
    llvm::Value *Mask =
2396
33
        Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2397
33
    llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2398
33
    TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2399
33
  }
2400
442
  llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2401
442
      CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2402
2403
442
  if (!SanOpts.has(SanitizerKind::Alignment))
2404
409
    return;
2405
33
  emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2406
33
                               OffsetValue, TheCheck, Assumption);
2407
33
}
2408
2409
void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2410
                                              const Expr *E,
2411
                                              SourceLocation AssumptionLoc,
2412
                                              llvm::Value *Alignment,
2413
408
                                              llvm::Value *OffsetValue) {
2414
408
  if (auto *CE = dyn_cast<CastExpr>(E))
2415
168
    E = CE->getSubExprAsWritten();
2416
408
  QualType Ty = E->getType();
2417
408
  SourceLocation Loc = E->getExprLoc();
2418
2419
408
  emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2420
408
                          OffsetValue);
2421
408
}
2422
2423
llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2424
                                                 llvm::Value *AnnotatedVal,
2425
                                                 StringRef AnnotationStr,
2426
                                                 SourceLocation Location,
2427
28
                                                 const AnnotateAttr *Attr) {
2428
28
  SmallVector<llvm::Value *, 5> Args = {
2429
28
      AnnotatedVal,
2430
28
      Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2431
28
      Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2432
28
      CGM.EmitAnnotationLineNo(Location),
2433
28
  };
2434
28
  if (Attr)
2435
21
    Args.push_back(CGM.EmitAnnotationArgs(Attr));
2436
28
  return Builder.CreateCall(AnnotationFn, Args);
2437
28
}
2438
2439
8
void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2440
8
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2441
  // FIXME We create a new bitcast for every annotation because that's what
2442
  // llvm-gcc was doing.
2443
0
  for (const auto *I : D->specific_attrs<AnnotateAttr>())
2444
12
    EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2445
12
                       Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2446
12
                       I->getAnnotation(), D->getLocation(), I);
2447
8
}
2448
2449
Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2450
5
                                              Address Addr) {
2451
5
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2452
0
  llvm::Value *V = Addr.getPointer();
2453
5
  llvm::Type *VTy = V->getType();
2454
5
  auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2455
5
  unsigned AS = PTy ? PTy->getAddressSpace() : 
00
;
2456
5
  llvm::PointerType *IntrinTy =
2457
5
      llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
2458
5
  llvm::Function *F =
2459
5
      CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
2460
2461
9
  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2462
    // FIXME Always emit the cast inst so we can differentiate between
2463
    // annotation on the first field of a struct and annotation on the struct
2464
    // itself.
2465
9
    if (VTy != IntrinTy)
2466
9
      V = Builder.CreateBitCast(V, IntrinTy);
2467
9
    V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2468
9
    V = Builder.CreateBitCast(V, VTy);
2469
9
  }
2470
2471
5
  return Address(V, Addr.getAlignment());
2472
5
}
2473
2474
69.0k
CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2475
2476
CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2477
58.4k
    : CGF(CGF) {
2478
58.4k
  assert(!CGF->IsSanitizerScope);
2479
0
  CGF->IsSanitizerScope = true;
2480
58.4k
}
2481
2482
58.4k
CodeGenFunction::SanitizerScope::~SanitizerScope() {
2483
58.4k
  CGF->IsSanitizerScope = false;
2484
58.4k
}
2485
2486
void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2487
                                   const llvm::Twine &Name,
2488
                                   llvm::BasicBlock *BB,
2489
5.82M
                                   llvm::BasicBlock::iterator InsertPt) const {
2490
5.82M
  LoopStack.InsertHelper(I);
2491
5.82M
  if (IsSanitizerScope)
2492
15.6k
    CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2493
5.82M
}
2494
2495
void CGBuilderInserter::InsertHelper(
2496
    llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2497
5.83M
    llvm::BasicBlock::iterator InsertPt) const {
2498
5.83M
  llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2499
5.83M
  if (CGF)
2500
5.82M
    CGF->InsertHelper(I, Name, BB, InsertPt);
2501
5.83M
}
2502
2503
// Emits an error if we don't have a valid set of target features for the
2504
// called function.
2505
void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2506
55.0k
                                          const FunctionDecl *TargetDecl) {
2507
55.0k
  return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2508
55.0k
}
2509
2510
// Emits an error if we don't have a valid set of target features for the
2511
// called function.
2512
void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2513
68.2k
                                          const FunctionDecl *TargetDecl) {
2514
  // Early exit if this is an indirect call.
2515
68.2k
  if (!TargetDecl)
2516
0
    return;
2517
2518
  // Get the current enclosing function if it exists. If it doesn't
2519
  // we can't check the target features anyhow.
2520
68.2k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2521
68.2k
  if (!FD)
2522
0
    return;
2523
2524
  // Grab the required features for the call. For a builtin this is listed in
2525
  // the td file with the default cpu, for an always_inline function this is any
2526
  // listed cpu and any listed features.
2527
68.2k
  unsigned BuiltinID = TargetDecl->getBuiltinID();
2528
68.2k
  std::string MissingFeature;
2529
68.2k
  llvm::StringMap<bool> CallerFeatureMap;
2530
68.2k
  CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2531
68.2k
  if (BuiltinID) {
2532
55.0k
    StringRef FeatureList(
2533
55.0k
        CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2534
    // Return if the builtin doesn't have any required features.
2535
55.0k
    if (FeatureList.empty())
2536
40.9k
      return;
2537
14.0k
    assert(!FeatureList.contains(' ') && "Space in feature list");
2538
0
    TargetFeatures TF(CallerFeatureMap);
2539
14.0k
    if (!TF.hasRequiredFeatures(FeatureList))
2540
466
      CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2541
466
          << TargetDecl->getDeclName() << FeatureList;
2542
14.0k
  } else 
if (13.1k
!TargetDecl->isMultiVersion()13.1k
&&
2543
13.1k
             TargetDecl->hasAttr<TargetAttr>()) {
2544
    // Get the required features for the callee.
2545
2546
13.1k
    const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2547
13.1k
    ParsedTargetAttr ParsedAttr =
2548
13.1k
        CGM.getContext().filterFunctionTargetAttrs(TD);
2549
2550
13.1k
    SmallVector<StringRef, 1> ReqFeatures;
2551
13.1k
    llvm::StringMap<bool> CalleeFeatureMap;
2552
13.1k
    CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2553
2554
14.8k
    for (const auto &F : ParsedAttr.Features) {
2555
14.8k
      if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2556
14.8k
        ReqFeatures.push_back(StringRef(F).substr(1));
2557
14.8k
    }
2558
2559
214k
    for (const auto &F : CalleeFeatureMap) {
2560
      // Only positive features are "required".
2561
214k
      if (F.getValue())
2562
214k
        ReqFeatures.push_back(F.getKey());
2563
214k
    }
2564
229k
    if (
!llvm::all_of(ReqFeatures, [&](StringRef Feature) 13.1k
{
2565
229k
      if (!CallerFeatureMap.lookup(Feature)) {
2566
19
        MissingFeature = Feature.str();
2567
19
        return false;
2568
19
      }
2569
229k
      return true;
2570
229k
    }))
2571
19
      CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2572
19
          << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2573
13.1k
  }
2574
68.2k
}
2575
2576
87
void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2577
87
  if (!CGM.getCodeGenOpts().SanitizeStats)
2578
77
    return;
2579
2580
10
  llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2581
10
  IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2582
10
  CGM.getSanStats().create(IRB, SSK);
2583
10
}
2584
2585
llvm::Value *
2586
326
CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2587
326
  llvm::Value *Condition = nullptr;
2588
2589
326
  if (!RO.Conditions.Architecture.empty())
2590
100
    Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2591
2592
326
  if (!RO.Conditions.Features.empty()) {
2593
132
    llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2594
132
    Condition =
2595
132
        Condition ? 
Builder.CreateAnd(Condition, FeatureCond)2
:
FeatureCond130
;
2596
132
  }
2597
326
  return Condition;
2598
326
}
2599
2600
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2601
                                             llvm::Function *Resolver,
2602
                                             CGBuilderTy &Builder,
2603
                                             llvm::Function *FuncToReturn,
2604
326
                                             bool SupportsIFunc) {
2605
326
  if (SupportsIFunc) {
2606
164
    Builder.CreateRet(FuncToReturn);
2607
164
    return;
2608
164
  }
2609
2610
162
  llvm::SmallVector<llvm::Value *, 10> Args;
2611
162
  llvm::for_each(Resolver->args(),
2612
162
                 [&](llvm::Argument &Arg) 
{ Args.push_back(&Arg); }152
);
2613
2614
162
  llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2615
162
  Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2616
2617
162
  if (Resolver->getReturnType()->isVoidTy())
2618
40
    Builder.CreateRetVoid();
2619
122
  else
2620
122
    Builder.CreateRet(Result);
2621
162
}
2622
2623
void CodeGenFunction::EmitMultiVersionResolver(
2624
112
    llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2625
112
  assert(getContext().getTargetInfo().getTriple().isX86() &&
2626
112
         "Only implemented for x86 targets");
2627
2628
0
  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2629
2630
  // Main function's basic block.
2631
112
  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2632
112
  Builder.SetInsertPoint(CurBlock);
2633
112
  EmitX86CpuInit();
2634
2635
326
  for (const MultiVersionResolverOption &RO : Options) {
2636
326
    Builder.SetInsertPoint(CurBlock);
2637
326
    llvm::Value *Condition = FormResolverCondition(RO);
2638
2639
    // The 'default' or 'generic' case.
2640
326
    if (!Condition) {
2641
96
      assert(&RO == Options.end() - 1 &&
2642
96
             "Default or Generic case must be last");
2643
0
      CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2644
96
                                       SupportsIFunc);
2645
96
      return;
2646
96
    }
2647
2648
230
    llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2649
230
    CGBuilderTy RetBuilder(*this, RetBlock);
2650
230
    CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2651
230
                                     SupportsIFunc);
2652
230
    CurBlock = createBasicBlock("resolver_else", Resolver);
2653
230
    Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2654
230
  }
2655
2656
  // If no generic/default, emit an unreachable.
2657
16
  Builder.SetInsertPoint(CurBlock);
2658
16
  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2659
16
  TrapCall->setDoesNotReturn();
2660
16
  TrapCall->setDoesNotThrow();
2661
16
  Builder.CreateUnreachable();
2662
16
  Builder.ClearInsertionPoint();
2663
16
}
2664
2665
// Loc - where the diagnostic will point, where in the source code this
2666
//  alignment has failed.
2667
// SecondaryLoc - if present (will be present if sufficiently different from
2668
//  Loc), the diagnostic will additionally point a "Note:" to this location.
2669
//  It should be the location where the __attribute__((assume_aligned))
2670
//  was written e.g.
2671
void CodeGenFunction::emitAlignmentAssumptionCheck(
2672
    llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2673
    SourceLocation SecondaryLoc, llvm::Value *Alignment,
2674
    llvm::Value *OffsetValue, llvm::Value *TheCheck,
2675
33
    llvm::Instruction *Assumption) {
2676
33
  assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2677
33
         cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2678
33
             llvm::Intrinsic::getDeclaration(
2679
33
                 Builder.GetInsertBlock()->getParent()->getParent(),
2680
33
                 llvm::Intrinsic::assume) &&
2681
33
         "Assumption should be a call to llvm.assume().");
2682
0
  assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2683
33
         "Assumption should be the last instruction of the basic block, "
2684
33
         "since the basic block is still being generated.");
2685
2686
33
  if (!SanOpts.has(SanitizerKind::Alignment))
2687
0
    return;
2688
2689
  // Don't check pointers to volatile data. The behavior here is implementation-
2690
  // defined.
2691
33
  if (Ty->getPointeeType().isVolatileQualified())
2692
1
    return;
2693
2694
  // We need to temorairly remove the assumption so we can insert the
2695
  // sanitizer check before it, else the check will be dropped by optimizations.
2696
32
  Assumption->removeFromParent();
2697
2698
32
  {
2699
32
    SanitizerScope SanScope(this);
2700
2701
32
    if (!OffsetValue)
2702
23
      OffsetValue = Builder.getInt1(false); // no offset.
2703
2704
32
    llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2705
32
                                    EmitCheckSourceLocation(SecondaryLoc),
2706
32
                                    EmitCheckTypeDescriptor(Ty)};
2707
32
    llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2708
32
                                  EmitCheckValue(Alignment),
2709
32
                                  EmitCheckValue(OffsetValue)};
2710
32
    EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2711
32
              SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2712
32
  }
2713
2714
  // We are now in the (new, empty) "cont" basic block.
2715
  // Reintroduce the assumption.
2716
32
  Builder.Insert(Assumption);
2717
  // FIXME: Assumption still has it's original basic block as it's Parent.
2718
32
}
2719
2720
69.7k
llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2721
69.7k
  if (CGDebugInfo *DI = getDebugInfo())
2722
31.1k
    return DI->SourceLocToDebugLoc(Location);
2723
2724
38.6k
  return llvm::DebugLoc();
2725
69.7k
}
2726
2727
llvm::Value *
2728
CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2729
150k
                                                      Stmt::Likelihood LH) {
2730
150k
  switch (LH) {
2731
150k
  case Stmt::LH_None:
2732
150k
    return Cond;
2733
17
  case Stmt::LH_Likely:
2734
58
  case Stmt::LH_Unlikely:
2735
    // Don't generate llvm.expect on -O0 as the backend won't use it for
2736
    // anything.
2737
58
    if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2738
0
      return Cond;
2739
58
    llvm::Type *CondTy = Cond->getType();
2740
58
    assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2741
0
    llvm::Function *FnExpect =
2742
58
        CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2743
58
    llvm::Value *ExpectedValueOfCond =
2744
58
        llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2745
58
    return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2746
58
                              Cond->getName() + ".expval");
2747
150k
  }
2748
0
  llvm_unreachable("Unknown Likelihood");
2749
0
}