Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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 "CGCleanup.h"
16
#include "CGCUDARuntime.h"
17
#include "CGCXXABI.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/Decl.h"
26
#include "clang/AST/DeclCXX.h"
27
#include "clang/AST/StmtCXX.h"
28
#include "clang/AST/StmtObjC.h"
29
#include "clang/Basic/Builtins.h"
30
#include "clang/Basic/CodeGenOptions.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "clang/CodeGen/CGFunctionInfo.h"
33
#include "clang/Frontend/FrontendDiagnostic.h"
34
#include "llvm/IR/DataLayout.h"
35
#include "llvm/IR/Dominators.h"
36
#include "llvm/IR/Intrinsics.h"
37
#include "llvm/IR/MDBuilder.h"
38
#include "llvm/IR/Operator.h"
39
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
40
using namespace clang;
41
using namespace CodeGen;
42
43
/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
44
/// markers.
45
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
46
388k
                                      const LangOptions &LangOpts) {
47
388k
  if (CGOpts.DisableLifetimeMarkers)
48
7
    return false;
49
388k
50
388k
  // Disable lifetime markers in msan builds.
51
388k
  // FIXME: Remove this when msan works with lifetime markers.
52
388k
  if (LangOpts.Sanitize.has(SanitizerKind::Memory))
53
198
    return false;
54
387k
55
387k
  // Asan uses markers for use-after-scope checks.
56
387k
  if (CGOpts.SanitizeAddressUseAfterScope)
57
35
    return true;
58
387k
59
387k
  // For now, only in optimized builds.
60
387k
  return CGOpts.OptimizationLevel != 0;
61
387k
}
62
63
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
64
    : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
65
      Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
66
              CGBuilderInserterTy(this)),
67
      SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
68
      PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
69
388k
                    CGM.getCodeGenOpts(), CGM.getLangOpts())) {
70
388k
  if (!suppressNewContext)
71
372k
    CGM.getCXXABI().getMangleContext().startNewFunction();
72
388k
73
388k
  llvm::FastMathFlags FMF;
74
388k
  if (CGM.getLangOpts().FastMath)
75
454
    FMF.setFast();
76
388k
  if (CGM.getLangOpts().FiniteMathOnly) {
77
400
    FMF.setNoNaNs();
78
400
    FMF.setNoInfs();
79
400
  }
80
388k
  if (CGM.getCodeGenOpts().NoNaNsFPMath) {
81
416
    FMF.setNoNaNs();
82
416
  }
83
388k
  if (CGM.getCodeGenOpts().NoSignedZeros) {
84
402
    FMF.setNoSignedZeros();
85
402
  }
86
388k
  if (CGM.getCodeGenOpts().ReciprocalMath) {
87
398
    FMF.setAllowReciprocal();
88
398
  }
89
388k
  if (CGM.getCodeGenOpts().Reassociate) {
90
398
    FMF.setAllowReassoc();
91
398
  }
92
388k
  Builder.setFastMathFlags(FMF);
93
388k
}
94
95
388k
CodeGenFunction::~CodeGenFunction() {
96
388k
  assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
97
388k
98
388k
  // If there are any unclaimed block infos, go ahead and destroy them
99
388k
  // now.  This can happen if IR-gen gets clever and skips evaluating
100
388k
  // something.
101
388k
  if (FirstBlockInfo)
102
0
    destroyBlockInfos(FirstBlockInfo);
103
388k
104
388k
  if (getLangOpts().OpenMP && 
CurFn43.7k
)
105
43.7k
    CGM.getOpenMPRuntime().functionFinished(*this);
106
388k
}
107
108
CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
109
                                                    LValueBaseInfo *BaseInfo,
110
690k
                                                    TBAAAccessInfo *TBAAInfo) {
111
690k
  return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
112
690k
                                 /* forPointeeType= */ true);
113
690k
}
114
115
CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
116
                                                   LValueBaseInfo *BaseInfo,
117
                                                   TBAAAccessInfo *TBAAInfo,
118
998k
                                                   bool forPointeeType) {
119
998k
  if (TBAAInfo)
120
935k
    *TBAAInfo = CGM.getTBAAAccessInfo(T);
121
998k
122
998k
  // Honor alignment typedef attributes even on incomplete types.
123
998k
  // We also honor them straight for C++ class types, even as pointees;
124
998k
  // there's an expressivity gap here.
125
998k
  if (auto TT = T->getAs<TypedefType>()) {
126
188k
    if (auto Align = TT->getDecl()->getMaxAlignment()) {
127
413
      if (BaseInfo)
128
413
        *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
129
413
      return getContext().toCharUnitsFromBits(Align);
130
413
    }
131
998k
  }
132
998k
133
998k
  if (BaseInfo)
134
972k
    *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
135
998k
136
998k
  CharUnits Alignment;
137
998k
  if (T->isIncompleteType()) {
138
1.52k
    Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
139
996k
  } else {
140
996k
    // For C++ class pointees, we don't know whether we're pointing at a
141
996k
    // base or a complete object, so we generally need to use the
142
996k
    // non-virtual alignment.
143
996k
    const CXXRecordDecl *RD;
144
996k
    if (forPointeeType && 
(RD = T->getAsCXXRecordDecl())964k
) {
145
583k
      Alignment = CGM.getClassPointerAlignment(RD);
146
583k
    } else {
147
413k
      Alignment = getContext().getTypeAlignInChars(T);
148
413k
      if (T.getQualifiers().hasUnaligned())
149
5
        Alignment = CharUnits::One();
150
413k
    }
151
996k
152
996k
    // Cap to the global maximum type alignment unless the alignment
153
996k
    // was somehow explicit on the type.
154
996k
    if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
155
902k
      if (Alignment.getQuantity() > MaxAlign &&
156
902k
          
!getContext().isAlignmentRequired(T)4.71k
)
157
3.20k
        Alignment = CharUnits::fromQuantity(MaxAlign);
158
902k
    }
159
996k
  }
160
998k
  return Alignment;
161
998k
}
162
163
31.8k
LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
164
31.8k
  LValueBaseInfo BaseInfo;
165
31.8k
  TBAAAccessInfo TBAAInfo;
166
31.8k
  CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
167
31.8k
  return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
168
31.8k
                          TBAAInfo);
169
31.8k
}
170
171
/// Given a value of type T* that may not be to a complete object,
172
/// construct an l-value with the natural pointee alignment of T.
173
LValue
174
119k
CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
175
119k
  LValueBaseInfo BaseInfo;
176
119k
  TBAAAccessInfo TBAAInfo;
177
119k
  CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
178
119k
                                            /* forPointeeType= */ true);
179
119k
  return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
180
119k
}
181
182
183
1.42M
llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
184
1.42M
  return CGM.getTypes().ConvertTypeForMem(T);
185
1.42M
}
186
187
5.37M
llvm::Type *CodeGenFunction::ConvertType(QualType T) {
188
5.37M
  return CGM.getTypes().ConvertType(T);
189
5.37M
}
190
191
6.78M
TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
192
6.78M
  type = type.getCanonicalType();
193
6.78M
  while (true) {
194
6.78M
    switch (type->getTypeClass()) {
195
6.78M
#define TYPE(name, parent)
196
6.78M
#define ABSTRACT_TYPE(name, parent)
197
6.78M
#define NON_CANONICAL_TYPE(name, parent) 
case Type::name:0
198
6.78M
#define DEPENDENT_TYPE(name, parent) 
case Type::name:0
199
6.78M
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) 
case Type::name:0
200
6.78M
#include "clang/AST/TypeNodes.def"
201
0
      llvm_unreachable("non-canonical or dependent type in IR-generation");
202
0
203
0
    case Type::Auto:
204
0
    case Type::DeducedTemplateSpecialization:
205
0
      llvm_unreachable("undeduced type in IR-generation");
206
0
207
0
    // Various scalar types.
208
6.55M
    case Type::Builtin:
209
6.55M
    case Type::Pointer:
210
6.55M
    case Type::BlockPointer:
211
6.55M
    case Type::LValueReference:
212
6.55M
    case Type::RValueReference:
213
6.55M
    case Type::MemberPointer:
214
6.55M
    case Type::Vector:
215
6.55M
    case Type::ExtVector:
216
6.55M
    case Type::FunctionProto:
217
6.55M
    case Type::FunctionNoProto:
218
6.55M
    case Type::Enum:
219
6.55M
    case Type::ObjCObjectPointer:
220
6.55M
    case Type::Pipe:
221
6.55M
      return TEK_Scalar;
222
6.55M
223
6.55M
    // Complexes.
224
6.55M
    case Type::Complex:
225
5.85k
      return TEK_Complex;
226
6.55M
227
6.55M
    // Arrays, records, and Objective-C objects.
228
6.55M
    case Type::ConstantArray:
229
226k
    case Type::IncompleteArray:
230
226k
    case Type::VariableArray:
231
226k
    case Type::Record:
232
226k
    case Type::ObjCObject:
233
226k
    case Type::ObjCInterface:
234
226k
      return TEK_Aggregate;
235
226k
236
226k
    // We operate on atomic values according to their underlying type.
237
226k
    case Type::Atomic:
238
90
      type = cast<AtomicType>(type)->getValueType();
239
90
      continue;
240
0
    }
241
0
    llvm_unreachable("unknown type kind!");
242
0
  }
243
6.78M
}
244
245
386k
llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
246
386k
  // For cleanliness, we try to avoid emitting the return block for
247
386k
  // simple cases.
248
386k
  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
249
386k
250
386k
  if (CurBB) {
251
194k
    assert(!CurBB->getTerminator() && "Unexpected terminated block.");
252
194k
253
194k
    // We have a valid insert point, reuse it if it is empty or there are no
254
194k
    // explicit jumps to the return block.
255
194k
    if (CurBB->empty() || 
ReturnBlock.getBlock()->use_empty()172k
) {
256
192k
      ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
257
192k
      delete ReturnBlock.getBlock();
258
192k
      ReturnBlock = JumpDest();
259
192k
    } else
260
2.75k
      EmitBlock(ReturnBlock.getBlock());
261
194k
    return llvm::DebugLoc();
262
194k
  }
263
191k
264
191k
  // Otherwise, if the return block is the target of a single direct
265
191k
  // branch then we can just put the code in that block instead. This
266
191k
  // cleans up functions which started with a unified return block.
267
191k
  if (ReturnBlock.getBlock()->hasOneUse()) {
268
180k
    llvm::BranchInst *BI =
269
180k
      dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
270
180k
    if (BI && 
BI->isUnconditional()180k
&&
271
180k
        
BI->getSuccessor(0) == ReturnBlock.getBlock()180k
) {
272
180k
      // Record/return the DebugLoc of the simple 'return' expression to be used
273
180k
      // later by the actual 'ret' instruction.
274
180k
      llvm::DebugLoc Loc = BI->getDebugLoc();
275
180k
      Builder.SetInsertPoint(BI->getParent());
276
180k
      BI->eraseFromParent();
277
180k
      delete ReturnBlock.getBlock();
278
180k
      ReturnBlock = JumpDest();
279
180k
      return Loc;
280
180k
    }
281
11.5k
  }
282
11.5k
283
11.5k
  // FIXME: We are at an unreachable point, there is no reason to emit the block
284
11.5k
  // unless it has uses. However, we still need a place to put the debug
285
11.5k
  // region.end for now.
286
11.5k
287
11.5k
  EmitBlock(ReturnBlock.getBlock());
288
11.5k
  return llvm::DebugLoc();
289
11.5k
}
290
291
1.54M
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
292
1.54M
  if (!BB) 
return1.53M
;
293
16.1k
  if (!BB->use_empty())
294
16.1k
    return CGF.CurFn->getBasicBlockList().push_back(BB);
295
7
  delete BB;
296
7
}
297
298
386k
void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
299
386k
  assert(BreakContinueStack.empty() &&
300
386k
         "mismatched push/pop in break/continue stack!");
301
386k
302
386k
  bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
303
386k
    && 
NumSimpleReturnExprs == NumReturnExprs30.5k
304
386k
    && 
ReturnBlock.getBlock()->use_empty()17.0k
;
305
386k
  // Usually the return expression is evaluated before the cleanup
306
386k
  // code.  If the function contains only a simple return statement,
307
386k
  // such as a constant, the location before the cleanup code becomes
308
386k
  // the last useful breakpoint in the function, because the simple
309
386k
  // return expression will be evaluated after the cleanup code. To be
310
386k
  // safe, set the debug location for cleanup code to the location of
311
386k
  // the return statement.  Otherwise the cleanup code should be at the
312
386k
  // end of the function's lexical scope.
313
386k
  //
314
386k
  // If there are multiple branches to the return block, the branch
315
386k
  // instructions will get the location of the return statements and
316
386k
  // all will be fine.
317
386k
  if (CGDebugInfo *DI = getDebugInfo()) {
318
117k
    if (OnlySimpleReturnStmts)
319
1.38k
      DI->EmitLocation(Builder, LastStopPoint);
320
115k
    else
321
115k
      DI->EmitLocation(Builder, EndLoc);
322
117k
  }
323
386k
324
386k
  // Pop any cleanups that might have been associated with the
325
386k
  // parameters.  Do this in whatever block we're currently in; it's
326
386k
  // important to do this before we enter the return block or return
327
386k
  // edges will be *really* confused.
328
386k
  bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
329
386k
  bool HasOnlyLifetimeMarkers =
330
386k
      HasCleanups && 
EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth)61.3k
;
331
386k
  bool EmitRetDbgLoc = !HasCleanups || 
HasOnlyLifetimeMarkers61.3k
;
332
386k
  if (HasCleanups) {
333
61.3k
    // Make sure the line table doesn't jump back into the body for
334
61.3k
    // the ret after it's been at EndLoc.
335
61.3k
    if (CGDebugInfo *DI = getDebugInfo())
336
26.7k
      if (OnlySimpleReturnStmts)
337
1.38k
        DI->EmitLocation(Builder, EndLoc);
338
61.3k
339
61.3k
    PopCleanupBlocks(PrologueCleanupDepth);
340
61.3k
  }
341
386k
342
386k
  // Emit function epilog (to return).
343
386k
  llvm::DebugLoc Loc = EmitReturnBlock();
344
386k
345
386k
  if (ShouldInstrumentFunction()) {
346
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
347
6
      CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
348
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
349
4
      CurFn->addFnAttr("instrument-function-exit-inlined",
350
4
                       "__cyg_profile_func_exit");
351
11
  }
352
386k
353
386k
  // Emit debug descriptor for function end.
354
386k
  if (CGDebugInfo *DI = getDebugInfo())
355
117k
    DI->EmitFunctionEnd(Builder, CurFn);
356
386k
357
386k
  // Reset the debug location to that of the simple 'return' expression, if any
358
386k
  // rather than that of the end of the function's scope '}'.
359
386k
  ApplyDebugLocation AL(*this, Loc);
360
386k
  EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
361
386k
  EmitEndEHSpec(CurCodeDecl);
362
386k
363
386k
  assert(EHStack.empty() &&
364
386k
         "did not remove all scopes from cleanup stack!");
365
386k
366
386k
  // If someone did an indirect goto, emit the indirect goto block at the end of
367
386k
  // the function.
368
386k
  if (IndirectBranch) {
369
34
    EmitBlock(IndirectBranch->getParent());
370
34
    Builder.ClearInsertionPoint();
371
34
  }
372
386k
373
386k
  // If some of our locals escaped, insert a call to llvm.localescape in the
374
386k
  // entry block.
375
386k
  if (!EscapedLocals.empty()) {
376
31
    // Invert the map from local to index into a simple vector. There should be
377
31
    // no holes.
378
31
    SmallVector<llvm::Value *, 4> EscapeArgs;
379
31
    EscapeArgs.resize(EscapedLocals.size());
380
31
    for (auto &Pair : EscapedLocals)
381
36
      EscapeArgs[Pair.second] = Pair.first;
382
31
    llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
383
31
        &CGM.getModule(), llvm::Intrinsic::localescape);
384
31
    CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
385
31
  }
386
386k
387
386k
  // Remove the AllocaInsertPt instruction, which is just a convenience for us.
388
386k
  llvm::Instruction *Ptr = AllocaInsertPt;
389
386k
  AllocaInsertPt = nullptr;
390
386k
  Ptr->eraseFromParent();
391
386k
392
386k
  // If someone took the address of a label but never did an indirect goto, we
393
386k
  // made a zero entry PHI node, which is illegal, zap it now.
394
386k
  if (IndirectBranch) {
395
34
    llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
396
34
    if (PN->getNumIncomingValues() == 0) {
397
12
      PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
398
12
      PN->eraseFromParent();
399
12
    }
400
34
  }
401
386k
402
386k
  EmitIfUsed(*this, EHResumeBlock);
403
386k
  EmitIfUsed(*this, TerminateLandingPad);
404
386k
  EmitIfUsed(*this, TerminateHandler);
405
386k
  EmitIfUsed(*this, UnreachableBlock);
406
386k
407
386k
  for (const auto &FuncletAndParent : TerminateFunclets)
408
17
    EmitIfUsed(*this, FuncletAndParent.second);
409
386k
410
386k
  if (CGM.getCodeGenOpts().EmitDeclMetadata)
411
0
    EmitDeclMetadata();
412
386k
413
386k
  for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
414
386k
           I = DeferredReplacements.begin(),
415
386k
           E = DeferredReplacements.end();
416
386k
       I != E; 
++I94
) {
417
94
    I->first->replaceAllUsesWith(I->second);
418
94
    I->first->eraseFromParent();
419
94
  }
420
386k
421
386k
  // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
422
386k
  // PHIs if the current function is a coroutine. We don't do it for all
423
386k
  // functions as it may result in slight increase in numbers of instructions
424
386k
  // if compiled with no optimizations. We do it for coroutine as the lifetime
425
386k
  // of CleanupDestSlot alloca make correct coroutine frame building very
426
386k
  // difficult.
427
386k
  if (NormalCleanupDest.isValid() && 
isCoroutine()21.1k
) {
428
41
    llvm::DominatorTree DT(*CurFn);
429
41
    llvm::PromoteMemToReg(
430
41
        cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
431
41
    NormalCleanupDest = Address::invalid();
432
41
  }
433
386k
434
386k
  // Scan function arguments for vector width.
435
386k
  for (llvm::Argument &A : CurFn->args())
436
658k
    if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
437
67.7k
      LargestVectorWidth = std::max(LargestVectorWidth,
438
67.7k
                                    VT->getPrimitiveSizeInBits());
439
386k
440
386k
  // Update vector width based on return type.
441
386k
  if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
442
32.8k
    LargestVectorWidth = std::max(LargestVectorWidth,
443
32.8k
                                  VT->getPrimitiveSizeInBits());
444
386k
445
386k
  // Add the required-vector-width attribute. This contains the max width from:
446
386k
  // 1. min-vector-width attribute used in the source program.
447
386k
  // 2. Any builtins used that have a vector width specified.
448
386k
  // 3. Values passed in and out of inline assembly.
449
386k
  // 4. Width of vector arguments and return types for this function.
450
386k
  // 5. Width of vector aguments and return types for functions called by this
451
386k
  //    function.
452
386k
  CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
453
386k
454
386k
  // If we generated an unreachable return block, delete it now.
455
386k
  if (ReturnBlock.isValid() && 
ReturnBlock.getBlock()->use_empty()14.3k
) {
456
2.62k
    Builder.ClearInsertionPoint();
457
2.62k
    ReturnBlock.getBlock()->eraseFromParent();
458
2.62k
  }
459
386k
  if (ReturnValue.isValid()) {
460
230k
    auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
461
230k
    if (RetAlloca && 
RetAlloca->use_empty()226k
) {
462
189k
      RetAlloca->eraseFromParent();
463
189k
      ReturnValue = Address::invalid();
464
189k
    }
465
230k
  }
466
386k
}
467
468
/// ShouldInstrumentFunction - Return true if the current function should be
469
/// instrumented with __cyg_profile_func_* calls
470
773k
bool CodeGenFunction::ShouldInstrumentFunction() {
471
773k
  if (!CGM.getCodeGenOpts().InstrumentFunctions &&
472
773k
      
!CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining773k
&&
473
773k
      
!CGM.getCodeGenOpts().InstrumentFunctionEntryBare773k
)
474
773k
    return false;
475
32
  if (!CurFuncDecl || 
CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()28
)
476
10
    return false;
477
22
  return true;
478
22
}
479
480
/// ShouldXRayInstrument - Return true if the current function should be
481
/// instrumented with XRay nop sleds.
482
377k
bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
483
377k
  return CGM.getCodeGenOpts().XRayInstrumentFunctions;
484
377k
}
485
486
/// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
487
/// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
488
2
bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
489
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
490
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
491
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
492
1
              XRayInstrKind::Custom);
493
2
}
494
495
2
bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
496
2
  return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
497
2
         (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
498
2
          CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
499
1
              XRayInstrKind::Typed);
500
2
}
501
502
llvm::Constant *
503
CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
504
110
                                            llvm::Constant *Addr) {
505
110
  // Addresses stored in prologue data can't require run-time fixups and must
506
110
  // be PC-relative. Run-time fixups are undesirable because they necessitate
507
110
  // writable text segments, which are unsafe. And absolute addresses are
508
110
  // undesirable because they break PIE mode.
509
110
510
110
  // Add a layer of indirection through a private global. Taking its address
511
110
  // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
512
110
  auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
513
110
                                      /*isConstant=*/true,
514
110
                                      llvm::GlobalValue::PrivateLinkage, Addr);
515
110
516
110
  // Create a PC-relative address.
517
110
  auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
518
110
  auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
519
110
  auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
520
110
  return (IntPtrTy == Int32Ty)
521
110
             ? 
PCRelAsInt68
522
110
             : 
llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty)42
;
523
110
}
524
525
llvm::Value *
526
CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
527
8
                                          llvm::Value *EncodedAddr) {
528
8
  // Reconstruct the address of the global.
529
8
  auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
530
8
  auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
531
8
  auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
532
8
  auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
533
8
534
8
  // Load the original pointer through the global.
535
8
  return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
536
8
                            "decoded_addr");
537
8
}
538
539
void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
540
                                               llvm::Function *Fn)
541
1.44k
{
542
1.44k
  if (!FD->hasAttr<OpenCLKernelAttr>())
543
1.05k
    return;
544
392
545
392
  llvm::LLVMContext &Context = getLLVMContext();
546
392
547
392
  CGM.GenOpenCLArgMetadata(Fn, FD, this);
548
392
549
392
  if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
550
2
    QualType HintQTy = A->getTypeHint();
551
2
    const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
552
2
    bool IsSignedInteger =
553
2
        HintQTy->isSignedIntegerType() ||
554
2
        
(1
HintEltQTy1
&&
HintEltQTy->getElementType()->isSignedIntegerType()1
);
555
2
    llvm::Metadata *AttrMDArgs[] = {
556
2
        llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
557
2
            CGM.getTypes().ConvertType(A->getTypeHint()))),
558
2
        llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
559
2
            llvm::IntegerType::get(Context, 32),
560
2
            llvm::APInt(32, (uint64_t)(IsSignedInteger ? 
11
:
01
))))};
561
2
    Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
562
2
  }
563
392
564
392
  if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
565
1
    llvm::Metadata *AttrMDArgs[] = {
566
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
567
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
568
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
569
1
    Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
570
1
  }
571
392
572
392
  if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
573
7
    llvm::Metadata *AttrMDArgs[] = {
574
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
575
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
576
7
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
577
7
    Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
578
7
  }
579
392
580
392
  if (const OpenCLIntelReqdSubGroupSizeAttr *A =
581
1
          FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
582
1
    llvm::Metadata *AttrMDArgs[] = {
583
1
        llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
584
1
    Fn->setMetadata("intel_reqd_sub_group_size",
585
1
                    llvm::MDNode::get(Context, AttrMDArgs));
586
1
  }
587
392
}
588
589
/// Determine whether the function F ends with a return stmt.
590
156k
static bool endsWithReturn(const Decl* F) {
591
156k
  const Stmt *Body = nullptr;
592
156k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
593
128k
    Body = FD->getBody();
594
28.1k
  else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
595
720
    Body = OMD->getBody();
596
156k
597
156k
  if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
598
127k
    auto LastStmt = CS->body_rbegin();
599
127k
    if (LastStmt != CS->body_rend())
600
96.3k
      return isa<ReturnStmt>(*LastStmt);
601
60.0k
  }
602
60.0k
  return false;
603
60.0k
}
604
605
303
void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
606
303
  if (SanOpts.has(SanitizerKind::Thread)) {
607
4
    Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
608
4
    Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
609
4
  }
610
303
}
611
612
35
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
613
35
  auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
614
35
  if (!MD || 
!MD->getDeclName().getAsIdentifierInfo()3
||
615
35
      
!MD->getDeclName().getAsIdentifierInfo()->isStr("allocate")3
||
616
35
      
(2
MD->getNumParams() != 12
&&
MD->getNumParams() != 21
))
617
33
    return false;
618
2
619
2
  if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
620
0
    return false;
621
2
622
2
  if (MD->getNumParams() == 2) {
623
1
    auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
624
1
    if (!PT || !PT->isVoidPointerType() ||
625
1
        !PT->getPointeeType().isConstQualified())
626
0
      return false;
627
2
  }
628
2
629
2
  return true;
630
2
}
631
632
/// Return the UBSan prologue signature for \p FD if one is available.
633
static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
634
200
                                            const FunctionDecl *FD) {
635
200
  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
636
96
    if (!MD->isStatic())
637
90
      return nullptr;
638
110
  return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
639
110
}
640
641
void CodeGenFunction::StartFunction(GlobalDecl GD,
642
                                    QualType RetTy,
643
                                    llvm::Function *Fn,
644
                                    const CGFunctionInfo &FnInfo,
645
                                    const FunctionArgList &Args,
646
                                    SourceLocation Loc,
647
386k
                                    SourceLocation StartLoc) {
648
386k
  assert(!CurFn &&
649
386k
         "Do not use a CodeGenFunction object for more than one function");
650
386k
651
386k
  const Decl *D = GD.getDecl();
652
386k
653
386k
  DidCallStackSave = false;
654
386k
  CurCodeDecl = D;
655
386k
  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
656
356k
    if (FD->usesSEHTry())
657
99
      CurSEHParent = FD;
658
386k
  CurFuncDecl = (D ? 
D->getNonClosureContext()378k
:
nullptr8.63k
);
659
386k
  FnRetTy = RetTy;
660
386k
  CurFn = Fn;
661
386k
  CurFnInfo = &FnInfo;
662
386k
  assert(CurFn->isDeclaration() && "Function already has body?");
663
386k
664
386k
  // If this function has been blacklisted for any of the enabled sanitizers,
665
386k
  // disable the sanitizer for the function.
666
386k
  do {
667
386k
#define SANITIZER(NAME, ID)                                                    \
668
930k
  if (
SanOpts.empty()546k
) \
669
930k
    
break383k
; \
670
930k
  
if (163k
SanOpts.has(SanitizerKind::ID)163k
) \
671
163k
    
if (5.85k
CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)5.85k
) \
672
5.85k
      
SanOpts.set(SanitizerKind::ID, false)48
;
673
386k
674
386k
#include "clang/Basic/Sanitizers.def"
675
163k
#undef SANITIZER
676
163k
  } while (
03.07k
);
677
386k
678
386k
  if (D) {
679
378k
    // Apply the no_sanitize* attributes to SanOpts.
680
378k
    for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
681
1.20k
      SanitizerMask mask = Attr->getMask();
682
1.20k
      SanOpts.Mask &= ~mask;
683
1.20k
      if (mask & SanitizerKind::Address)
684
67
        SanOpts.set(SanitizerKind::KernelAddress, false);
685
1.20k
      if (mask & SanitizerKind::KernelAddress)
686
5
        SanOpts.set(SanitizerKind::Address, false);
687
1.20k
      if (mask & SanitizerKind::HWAddress)
688
5
        SanOpts.set(SanitizerKind::KernelHWAddress, false);
689
1.20k
      if (mask & SanitizerKind::KernelHWAddress)
690
5
        SanOpts.set(SanitizerKind::HWAddress, false);
691
1.20k
    }
692
378k
  }
693
386k
694
386k
  // Apply sanitizer attributes to the function.
695
386k
  if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
696
463
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
697
386k
  if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
698
28
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
699
386k
  if (SanOpts.has(SanitizerKind::MemTag))
700
1
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
701
386k
  if (SanOpts.has(SanitizerKind::Thread))
702
42
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
703
386k
  if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
704
201
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
705
386k
  if (SanOpts.has(SanitizerKind::SafeStack))
706
14
    Fn->addFnAttr(llvm::Attribute::SafeStack);
707
386k
  if (SanOpts.has(SanitizerKind::ShadowCallStack))
708
1
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
709
386k
710
386k
  // Apply fuzzing attribute to the function.
711
386k
  if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
712
0
    Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
713
386k
714
386k
  // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
715
386k
  // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
716
386k
  if (SanOpts.has(SanitizerKind::Thread)) {
717
42
    if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
718
3
      IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
719
3
      if (OMD->getMethodFamily() == OMF_dealloc ||
720
3
          
OMD->getMethodFamily() == OMF_initialize2
||
721
3
          
(1
OMD->getSelector().isUnarySelector()1
&&
II->isStr(".cxx_destruct")1
)) {
722
3
        markAsIgnoreThreadCheckingAtRuntime(Fn);
723
3
      }
724
3
    }
725
42
  }
726
386k
727
386k
  // Ignore unrelated casts in STL allocate() since the allocator must cast
728
386k
  // from void* to T* before object initialization completes. Don't match on the
729
386k
  // namespace because not all allocators are in std::
730
386k
  if (D && 
SanOpts.has(SanitizerKind::CFIUnrelatedCast)378k
) {
731
35
    if (matchesStlAllocatorFn(D, getContext()))
732
2
      SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
733
35
  }
734
386k
735
386k
  // Apply xray attributes to the function (as a string, for now)
736
386k
  if (D) {
737
378k
    if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
738
917
      if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
739
917
              XRayInstrKind::Function)) {
740
913
        if (XRayAttr->alwaysXRayInstrument() && 
ShouldXRayInstrumentFunction()39
)
741
32
          Fn->addFnAttr("function-instrument", "xray-always");
742
913
        if (XRayAttr->neverXRayInstrument())
743
874
          Fn->addFnAttr("function-instrument", "xray-never");
744
913
        if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
745
1
          if (ShouldXRayInstrumentFunction())
746
1
            Fn->addFnAttr("xray-log-args",
747
1
                          llvm::utostr(LogArgs->getArgumentCount()));
748
913
      }
749
377k
    } else {
750
377k
      if (ShouldXRayInstrumentFunction() && 
!CGM.imbueXRayAttrs(Fn, Loc)17
)
751
5
        Fn->addFnAttr(
752
5
            "xray-instruction-threshold",
753
5
            llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
754
377k
    }
755
378k
  }
756
386k
757
386k
  // Add no-jump-tables value.
758
386k
  Fn->addFnAttr("no-jump-tables",
759
386k
                llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
760
386k
761
386k
  // Add profile-sample-accurate value.
762
386k
  if (CGM.getCodeGenOpts().ProfileSampleAccurate)
763
2
    Fn->addFnAttr("profile-sample-accurate");
764
386k
765
386k
  if (getLangOpts().OpenCL) {
766
1.54k
    // Add metadata for a kernel function.
767
1.54k
    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
768
1.44k
      EmitOpenCLKernelMetadata(FD, Fn);
769
1.54k
  }
770
386k
771
386k
  // If we are checking function types, emit a function type signature as
772
386k
  // prologue data.
773
386k
  if (getLangOpts().CPlusPlus && 
SanOpts.has(SanitizerKind::Function)293k
) {
774
207
    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
775
200
      if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
776
110
        // Remove any (C++17) exception specifications, to allow calling e.g. a
777
110
        // noexcept function through a non-noexcept pointer.
778
110
        auto ProtoTy =
779
110
          getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
780
110
                                                        EST_None);
781
110
        llvm::Constant *FTRTTIConst =
782
110
            CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
783
110
        llvm::Constant *FTRTTIConstEncoded =
784
110
            EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
785
110
        llvm::Constant *PrologueStructElems[] = {PrologueSig,
786
110
                                                 FTRTTIConstEncoded};
787
110
        llvm::Constant *PrologueStructConst =
788
110
            llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
789
110
        Fn->setPrologueData(PrologueStructConst);
790
110
      }
791
200
    }
792
207
  }
793
386k
794
386k
  // If we're checking nullability, we need to know whether we can check the
795
386k
  // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
796
386k
  if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
797
4
    auto Nullability = FnRetTy->getNullability(getContext());
798
4
    if (Nullability && 
*Nullability == NullabilityKind::NonNull1
) {
799
1
      if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
800
1
            
CurCodeDecl0
&&
CurCodeDecl->getAttr<ReturnsNonNullAttr>()0
))
801
1
        RetValNullabilityPrecondition =
802
1
            llvm::ConstantInt::getTrue(getLLVMContext());
803
1
    }
804
4
  }
805
386k
806
386k
  // If we're in C++ mode and the function name is "main", it is guaranteed
807
386k
  // to be norecurse by the standard (3.6.1.3 "The function main shall not be
808
386k
  // used within a program").
809
386k
  if (getLangOpts().CPlusPlus)
810
293k
    if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
811
264k
      if (FD->isMain())
812
1.90k
        Fn->addFnAttr(llvm::Attribute::NoRecurse);
813
386k
814
386k
  // If a custom alignment is used, force realigning to this alignment on
815
386k
  // any main function which certainly will need it.
816
386k
  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
817
356k
    if ((FD->isMain() || 
FD->isMSVCRTEntryPoint()353k
) &&
818
356k
        
CGM.getCodeGenOpts().StackAlignment2.71k
)
819
1
      Fn->addFnAttr("stackrealign");
820
386k
821
386k
  llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
822
386k
823
386k
  // Create a marker to make it easy to insert allocas into the entryblock
824
386k
  // later.  Don't create this with the builder, because we don't want it
825
386k
  // folded.
826
386k
  llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
827
386k
  AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
828
386k
829
386k
  ReturnBlock = getJumpDestInCurrentScope("return");
830
386k
831
386k
  Builder.SetInsertPoint(EntryBB);
832
386k
833
386k
  // If we're checking the return value, allocate space for a pointer to a
834
386k
  // precise source location of the checked return statement.
835
386k
  if (requiresReturnValueCheck()) {
836
4
    ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
837
4
    InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
838
4
  }
839
386k
840
386k
  // Emit subprogram debug descriptor.
841
386k
  if (CGDebugInfo *DI = getDebugInfo()) {
842
117k
    // Reconstruct the type from the argument list so that implicit parameters,
843
117k
    // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
844
117k
    // convention.
845
117k
    CallingConv CC = CallingConv::CC_C;
846
117k
    if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
847
115k
      if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
848
115k
        CC = SrcFnTy->getCallConv();
849
117k
    SmallVector<QualType, 16> ArgTypes;
850
117k
    for (const VarDecl *VD : Args)
851
209k
      ArgTypes.push_back(VD->getType());
852
117k
    QualType FnType = getContext().getFunctionType(
853
117k
        RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
854
117k
    DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
855
117k
                          Builder);
856
117k
  }
857
386k
858
386k
  if (ShouldInstrumentFunction()) {
859
11
    if (CGM.getCodeGenOpts().InstrumentFunctions)
860
6
      CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
861
11
    if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
862
4
      CurFn->addFnAttr("instrument-function-entry-inlined",
863
4
                       "__cyg_profile_func_enter");
864
11
    if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
865
1
      CurFn->addFnAttr("instrument-function-entry-inlined",
866
1
                       "__cyg_profile_func_enter_bare");
867
11
  }
868
386k
869
386k
  // Since emitting the mcount call here impacts optimizations such as function
870
386k
  // inlining, we just add an attribute to insert a mcount call in backend.
871
386k
  // The attribute "counting-function" is set to mcount function name which is
872
386k
  // architecture dependent.
873
386k
  if (CGM.getCodeGenOpts().InstrumentForProfiling) {
874
113
    // Calls to fentry/mcount should not be generated if function has
875
113
    // the no_instrument_function attribute.
876
113
    if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
877
92
      if (CGM.getCodeGenOpts().CallFEntry)
878
2
        Fn->addFnAttr("fentry-call", "true");
879
90
      else {
880
90
        Fn->addFnAttr("instrument-function-entry-inlined",
881
90
                      getTarget().getMCountName());
882
90
      }
883
92
    }
884
113
  }
885
386k
886
386k
  if (RetTy->isVoidType()) {
887
156k
    // Void type; nothing to return.
888
156k
    ReturnValue = Address::invalid();
889
156k
890
156k
    // Count the implicit return.
891
156k
    if (!endsWithReturn(D))
892
154k
      ++NumReturnExprs;
893
230k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
894
4.25k
    // Indirect return; emit returned value directly into sret slot.
895
4.25k
    // This reduces code size, and affects correctness in C++.
896
4.25k
    auto AI = CurFn->arg_begin();
897
4.25k
    if (CurFnInfo->getReturnInfo().isSRetAfterThis())
898
44
      ++AI;
899
4.25k
    ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
900
4.25k
    if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
901
2.52k
      ReturnValuePointer =
902
2.52k
          CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
903
2.52k
      Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
904
2.52k
                              ReturnValue.getPointer(), Int8PtrTy),
905
2.52k
                          ReturnValuePointer);
906
2.52k
    }
907
226k
  } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
908
226k
             
!hasScalarEvaluationKind(CurFnInfo->getReturnType())5
) {
909
5
    // Load the sret pointer from the argument struct and return into that.
910
5
    unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
911
5
    llvm::Function::arg_iterator EI = CurFn->arg_end();
912
5
    --EI;
913
5
    llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
914
5
    ReturnValuePointer = Address(Addr, getPointerAlign());
915
5
    Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
916
5
    ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
917
226k
  } else {
918
226k
    ReturnValue = CreateIRTemp(RetTy, "retval");
919
226k
920
226k
    // Tell the epilog emitter to autorelease the result.  We do this
921
226k
    // now so that various specialized functions can suppress it
922
226k
    // during their IR-generation.
923
226k
    if (getLangOpts().ObjCAutoRefCount &&
924
226k
        
!CurFnInfo->isReturnsRetained()315
&&
925
226k
        
RetTy->isObjCRetainableType()281
)
926
122
      AutoreleaseResult = true;
927
226k
  }
928
386k
929
386k
  EmitStartEHSpec(CurCodeDecl);
930
386k
931
386k
  PrologueCleanupDepth = EHStack.stable_begin();
932
386k
933
386k
  // Emit OpenMP specific initialization of the device functions.
934
386k
  if (getLangOpts().OpenMP && 
CurCodeDecl43.7k
)
935
37.8k
    CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
936
386k
937
386k
  EmitFunctionProlog(*CurFnInfo, CurFn, Args);
938
386k
939
386k
  if (D && 
isa<CXXMethodDecl>(D)378k
&&
cast<CXXMethodDecl>(D)->isInstance()188k
) {
940
172k
    CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
941
172k
    const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
942
172k
    if (MD->getParent()->isLambda() &&
943
172k
        
MD->getOverloadedOperator() == OO_Call1.72k
) {
944
1.59k
      // We're in a lambda; figure out the captures.
945
1.59k
      MD->getParent()->getCaptureFields(LambdaCaptureFields,
946
1.59k
                                        LambdaThisCaptureField);
947
1.59k
      if (LambdaThisCaptureField) {
948
110
        // If the lambda captures the object referred to by '*this' - either by
949
110
        // value or by reference, make sure CXXThisValue points to the correct
950
110
        // object.
951
110
952
110
        // Get the lvalue for the field (which is a copy of the enclosing object
953
110
        // or contains the address of the enclosing object).
954
110
        LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
955
110
        if (!LambdaThisCaptureField->getType()->isPointerType()) {
956
1
          // If the enclosing object was captured by value, just use its address.
957
1
          CXXThisValue = ThisFieldLValue.getAddress().getPointer();
958
109
        } else {
959
109
          // Load the lvalue pointed to by the field, since '*this' was captured
960
109
          // by reference.
961
109
          CXXThisValue =
962
109
              EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
963
109
        }
964
110
      }
965
2.90k
      for (auto *FD : MD->getParent()->fields()) {
966
2.90k
        if (FD->hasCapturedVLAType()) {
967
24
          auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
968
24
                                           SourceLocation()).getScalarVal();
969
24
          auto VAT = FD->getCapturedVLAType();
970
24
          VLASizeMap[VAT->getSizeExpr()] = ExprArg;
971
24
        }
972
2.90k
      }
973
170k
    } else {
974
170k
      // Not in a lambda; just use 'this' from the method.
975
170k
      // FIXME: Should we generate a new load for each use of 'this'?  The
976
170k
      // fast register allocator would be happier...
977
170k
      CXXThisValue = CXXABIThisValue;
978
170k
    }
979
172k
980
172k
    // Check the 'this' pointer once per function, if it's available.
981
172k
    if (CXXABIThisValue) {
982
172k
      SanitizerSet SkippedChecks;
983
172k
      SkippedChecks.set(SanitizerKind::ObjectSize, true);
984
172k
      QualType ThisTy = MD->getThisType();
985
172k
986
172k
      // If this is the call operator of a lambda with no capture-default, it
987
172k
      // may have a static invoker function, which may call this operator with
988
172k
      // a null 'this' pointer.
989
172k
      if (isLambdaCallOperator(MD) &&
990
172k
          
MD->getParent()->getLambdaCaptureDefault() == LCD_None1.59k
)
991
330
        SkippedChecks.set(SanitizerKind::Null, true);
992
172k
993
172k
      EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? 
TCK_ConstructorCall52.0k
994
172k
                                                : 
TCK_MemberCall120k
,
995
172k
                    Loc, CXXABIThisValue, ThisTy,
996
172k
                    getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
997
172k
                    SkippedChecks);
998
172k
    }
999
172k
  }
1000
386k
1001
386k
  // If any of the arguments have a variably modified type, make sure to
1002
386k
  // emit the type size.
1003
386k
  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1004
1.04M
       i != e; 
++i657k
) {
1005
657k
    const VarDecl *VD = *i;
1006
657k
1007
657k
    // Dig out the type as written from ParmVarDecls; it's unclear whether
1008
657k
    // the standard (C99 6.9.1p10) requires this, but we're following the
1009
657k
    // precedent set by gcc.
1010
657k
    QualType Ty;
1011
657k
    if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1012
427k
      Ty = PVD->getOriginalType();
1013
230k
    else
1014
230k
      Ty = VD->getType();
1015
657k
1016
657k
    if (Ty->isVariablyModifiedType())
1017
96
      EmitVariablyModifiedType(Ty);
1018
657k
  }
1019
386k
  // Emit a location at the end of the prologue.
1020
386k
  if (CGDebugInfo *DI = getDebugInfo())
1021
117k
    DI->EmitLocation(Builder, StartLoc);
1022
386k
1023
386k
  // TODO: Do we need to handle this in two places like we do with
1024
386k
  // target-features/target-cpu?
1025
386k
  if (CurFuncDecl)
1026
372k
    if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1027
7.07k
      LargestVectorWidth = VecWidth->getVectorWidth();
1028
386k
}
1029
1030
279k
void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1031
279k
  incrementProfileCounter(Body);
1032
279k
  if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1033
278k
    EmitCompoundStmtWithoutScope(*S);
1034
46
  else
1035
46
    EmitStmt(Body);
1036
279k
}
1037
1038
/// When instrumenting to collect profile data, the counts for some blocks
1039
/// such as switch cases need to not include the fall-through counts, so
1040
/// emit a branch around the instrumentation code. When not instrumenting,
1041
/// this just calls EmitBlock().
1042
void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1043
47.1k
                                               const Stmt *S) {
1044
47.1k
  llvm::BasicBlock *SkipCountBB = nullptr;
1045
47.1k
  if (HaveInsertPoint() && 
CGM.getCodeGenOpts().hasProfileClangInstr()28.7k
) {
1046
22
    // When instrumenting for profiling, the fallthrough to certain
1047
22
    // statements needs to skip over the instrumentation code so that we
1048
22
    // get an accurate count.
1049
22
    SkipCountBB = createBasicBlock("skipcount");
1050
22
    EmitBranch(SkipCountBB);
1051
22
  }
1052
47.1k
  EmitBlock(BB);
1053
47.1k
  uint64_t CurrentCount = getCurrentProfileCount();
1054
47.1k
  incrementProfileCounter(S);
1055
47.1k
  setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1056
47.1k
  if (SkipCountBB)
1057
22
    EmitBlock(SkipCountBB);
1058
47.1k
}
1059
1060
/// Tries to mark the given function nounwind based on the
1061
/// non-existence of any throwing calls within it.  We believe this is
1062
/// lightweight enough to do at -O0.
1063
279k
static void TryMarkNoThrow(llvm::Function *F) {
1064
279k
  // LLVM treats 'nounwind' on a function as part of the type, so we
1065
279k
  // can't do this on functions that can be overwritten.
1066
279k
  if (F->isInterposable()) 
return639
;
1067
279k
1068
279k
  for (llvm::BasicBlock &BB : *F)
1069
537k
    for (llvm::Instruction &I : BB)
1070
4.99M
      if (I.mayThrow())
1071
154k
        return;
1072
279k
1073
279k
  F->setDoesNotThrow();
1074
124k
}
1075
1076
QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1077
355k
                                               FunctionArgList &Args) {
1078
355k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1079
355k
  QualType ResTy = FD->getReturnType();
1080
355k
1081
355k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1082
355k
  if (MD && 
MD->isInstance()188k
) {
1083
172k
    if (CGM.getCXXABI().HasThisReturn(GD))
1084
41.6k
      ResTy = MD->getThisType();
1085
130k
    else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1086
202
      ResTy = CGM.getContext().VoidPtrTy;
1087
172k
    CGM.getCXXABI().buildThisParam(*this, Args);
1088
172k
  }
1089
355k
1090
355k
  // The base version of an inheriting constructor whose constructed base is a
1091
355k
  // virtual base is not passed any arguments (because it doesn't actually call
1092
355k
  // the inherited constructor).
1093
355k
  bool PassedParams = true;
1094
355k
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1095
52.1k
    if (auto Inherited = CD->getInheritedConstructor())
1096
126
      PassedParams =
1097
126
          getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1098
355k
1099
355k
  if (PassedParams) {
1100
425k
    for (auto *Param : FD->parameters()) {
1101
425k
      Args.push_back(Param);
1102
425k
      if (!Param->hasAttr<PassObjectSizeAttr>())
1103
425k
        continue;
1104
88
1105
88
      auto *Implicit = ImplicitParamDecl::Create(
1106
88
          getContext(), Param->getDeclContext(), Param->getLocation(),
1107
88
          /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1108
88
      SizeArguments[Param] = Implicit;
1109
88
      Args.push_back(Implicit);
1110
88
    }
1111
355k
  }
1112
355k
1113
355k
  if (MD && 
(188k
isa<CXXConstructorDecl>(MD)188k
||
isa<CXXDestructorDecl>(MD)135k
))
1114
75.4k
    CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1115
355k
1116
355k
  return ResTy;
1117
355k
}
1118
1119
static bool
1120
shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
1121
21
                                             const ASTContext &Context) {
1122
21
  QualType T = FD->getReturnType();
1123
21
  // Avoid the optimization for functions that return a record type with a
1124
21
  // trivial destructor or another trivially copyable type.
1125
21
  if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
1126
12
    if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1127
12
      return !ClassDecl->hasTrivialDestructor();
1128
9
  }
1129
9
  return !T.isTriviallyCopyableType(Context);
1130
9
}
1131
1132
void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1133
355k
                                   const CGFunctionInfo &FnInfo) {
1134
355k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1135
355k
  CurGD = GD;
1136
355k
1137
355k
  FunctionArgList Args;
1138
355k
  QualType ResTy = BuildFunctionArgList(GD, Args);
1139
355k
1140
355k
  // Check if we should generate debug info for this function.
1141
355k
  if (FD->hasAttr<NoDebugAttr>())
1142
13.9k
    DebugInfo = nullptr; // disable debug info indefinitely for this function
1143
355k
1144
355k
  // The function might not have a body if we're generating thunks for a
1145
355k
  // function declaration.
1146
355k
  SourceRange BodyRange;
1147
355k
  if (Stmt *Body = FD->getBody())
1148
355k
    BodyRange = Body->getSourceRange();
1149
125
  else
1150
125
    BodyRange = FD->getLocation();
1151
355k
  CurEHLocation = BodyRange.getEnd();
1152
355k
1153
355k
  // Use the location of the start of the function to determine where
1154
355k
  // the function definition is located. By default use the location
1155
355k
  // of the declaration as the location for the subprogram. A function
1156
355k
  // may lack a declaration in the source code if it is created by code
1157
355k
  // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1158
355k
  SourceLocation Loc = FD->getLocation();
1159
355k
1160
355k
  // If this is a function specialization then use the pattern body
1161
355k
  // as the location for the function.
1162
355k
  if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1163
147k
    if (SpecDecl->hasBody(SpecDecl))
1164
146k
      Loc = SpecDecl->getLocation();
1165
355k
1166
355k
  Stmt *Body = FD->getBody();
1167
355k
1168
355k
  // Initialize helper which will detect jumps which can cause invalid lifetime
1169
355k
  // markers.
1170
355k
  if (Body && 
ShouldEmitLifetimeMarkers355k
)
1171
263k
    Bypasses.Init(Body);
1172
355k
1173
355k
  // Emit the standard function prologue.
1174
355k
  StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1175
355k
1176
355k
  // Generate the body of the function.
1177
355k
  PGO.assignRegionCounters(GD, CurFn);
1178
355k
  if (isa<CXXDestructorDecl>(FD))
1179
23.2k
    EmitDestructorBody(Args);
1180
331k
  else if (isa<CXXConstructorDecl>(FD))
1181
52.0k
    EmitConstructorBody(Args);
1182
279k
  else if (getLangOpts().CUDA &&
1183
279k
           
!getLangOpts().CUDAIsDevice322
&&
1184
279k
           
FD->hasAttr<CUDAGlobalAttr>()99
)
1185
22
    CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1186
279k
  else if (isa<CXXMethodDecl>(FD) &&
1187
279k
           
cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()112k
) {
1188
85
    // The lambda static invoker function is special, because it forwards or
1189
85
    // clones the body of the function call operator (but is actually static).
1190
85
    EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1191
279k
  } else if (FD->isDefaulted() && 
isa<CXXMethodDecl>(FD)771
&&
1192
279k
             
(771
cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator()771
||
1193
771
              
cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator()233
)) {
1194
771
    // Implicit copy-assignment gets the same special treatment as implicit
1195
771
    // copy-constructors.
1196
771
    emitImplicitAssignmentOperatorBody(Args);
1197
279k
  } else if (Body) {
1198
279k
    EmitFunctionBody(Body);
1199
279k
  } else
1200
279k
    
llvm_unreachable0
("no definition for emitted function");
1201
355k
1202
355k
  // C++11 [stmt.return]p2:
1203
355k
  //   Flowing off the end of a function [...] results in undefined behavior in
1204
355k
  //   a value-returning function.
1205
355k
  // C11 6.9.1p12:
1206
355k
  //   If the '}' that terminates a function is reached, and the value of the
1207
355k
  //   function call is used by the caller, the behavior is undefined.
1208
355k
  if (getLangOpts().CPlusPlus && 
!FD->hasImplicitReturnZero()264k
&&
!SawAsmBlock262k
&&
1209
355k
      
!FD->getReturnType()->isVoidType()262k
&&
Builder.GetInsertBlock()117k
) {
1210
618
    bool ShouldEmitUnreachable =
1211
618
        CGM.getCodeGenOpts().StrictReturn ||
1212
618
        
shouldUseUndefinedBehaviorReturnOptimization(FD, getContext())21
;
1213
618
    if (SanOpts.has(SanitizerKind::Return)) {
1214
1
      SanitizerScope SanScope(this);
1215
1
      llvm::Value *IsFalse = Builder.getFalse();
1216
1
      EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1217
1
                SanitizerHandler::MissingReturn,
1218
1
                EmitCheckSourceLocation(FD->getLocation()), None);
1219
617
    } else if (ShouldEmitUnreachable) {
1220
599
      if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1221
110
        EmitTrapCall(llvm::Intrinsic::trap);
1222
599
    }
1223
618
    if (SanOpts.has(SanitizerKind::Return) || 
ShouldEmitUnreachable617
) {
1224
600
      Builder.CreateUnreachable();
1225
600
      Builder.ClearInsertionPoint();
1226
600
    }
1227
618
  }
1228
355k
1229
355k
  // Emit the standard function epilogue.
1230
355k
  FinishFunction(BodyRange.getEnd());
1231
355k
1232
355k
  // If we haven't marked the function nothrow through other means, do
1233
355k
  // a quick pass now to see if we can.
1234
355k
  if (!CurFn->doesNotThrow())
1235
279k
    TryMarkNoThrow(CurFn);
1236
355k
}
1237
1238
/// ContainsLabel - Return true if the statement contains a label in it.  If
1239
/// this statement is not executed normally, it not containing a label means
1240
/// that we can just remove the code.
1241
759k
bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1242
759k
  // Null statement, not a label!
1243
759k
  if (!S) 
return false1.99k
;
1244
757k
1245
757k
  // If this is a label, we have to emit the code, consider something like:
1246
757k
  // if (0) {  ...  foo:  bar(); }  goto foo;
1247
757k
  //
1248
757k
  // TODO: If anyone cared, we could track __label__'s, since we know that you
1249
757k
  // can't jump to one from outside their declared region.
1250
757k
  if (isa<LabelStmt>(S))
1251
5
    return true;
1252
757k
1253
757k
  // If this is a case/default statement, and we haven't seen a switch, we have
1254
757k
  // to emit the code.
1255
757k
  if (isa<SwitchCase>(S) && 
!IgnoreCaseStmts140
)
1256
0
    return true;
1257
757k
1258
757k
  // If this is a switch statement, we want to ignore cases below it.
1259
757k
  if (isa<SwitchStmt>(S))
1260
10
    IgnoreCaseStmts = true;
1261
757k
1262
757k
  // Scan subexpressions for verboten labels.
1263
757k
  for (const Stmt *SubStmt : S->children())
1264
706k
    if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1265
11
      return true;
1266
757k
1267
757k
  
return false757k
;
1268
757k
}
1269
1270
/// containsBreak - Return true if the statement contains a break out of it.
1271
/// If the statement (recursively) contains a switch or loop with a break
1272
/// inside of it, this is fine.
1273
7.60k
bool CodeGenFunction::containsBreak(const Stmt *S) {
1274
7.60k
  // Null statement, not a label!
1275
7.60k
  if (!S) 
return false0
;
1276
7.60k
1277
7.60k
  // If this is a switch or loop that defines its own break scope, then we can
1278
7.60k
  // include it and anything inside of it.
1279
7.60k
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1280
7.60k
      
isa<ForStmt>(S)7.60k
)
1281
3
    return false;
1282
7.60k
1283
7.60k
  if (isa<BreakStmt>(S))
1284
1
    return true;
1285
7.60k
1286
7.60k
  // Scan subexpressions for verboten breaks.
1287
7.60k
  for (const Stmt *SubStmt : S->children())
1288
5.33k
    if (containsBreak(SubStmt))
1289
1
      return true;
1290
7.60k
1291
7.60k
  
return false7.60k
;
1292
7.60k
}
1293
1294
31.7k
bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1295
31.7k
  if (!S) 
return false0
;
1296
31.7k
1297
31.7k
  // Some statement kinds add a scope and thus never add a decl to the current
1298
31.7k
  // scope. Note, this list is longer than the list of statements that might
1299
31.7k
  // have an unscoped decl nested within them, but this way is conservatively
1300
31.7k
  // correct even if more statement kinds are added.
1301
31.7k
  if (isa<IfStmt>(S) || 
isa<SwitchStmt>(S)31.7k
||
isa<WhileStmt>(S)31.7k
||
1302
31.7k
      
isa<DoStmt>(S)31.7k
||
isa<ForStmt>(S)31.7k
||
isa<CompoundStmt>(S)31.7k
||
1303
31.7k
      
isa<CXXForRangeStmt>(S)31.7k
||
isa<CXXTryStmt>(S)31.7k
||
1304
31.7k
      
isa<ObjCForCollectionStmt>(S)31.7k
||
isa<ObjCAtTryStmt>(S)31.7k
)
1305
19
    return false;
1306
31.7k
1307
31.7k
  if (isa<DeclStmt>(S))
1308
7
    return true;
1309
31.7k
1310
31.7k
  for (const Stmt *SubStmt : S->children())
1311
27.2k
    if (mightAddDeclToScope(SubStmt))
1312
2
      return true;
1313
31.7k
1314
31.7k
  
return false31.7k
;
1315
31.7k
}
1316
1317
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1318
/// to a constant, or if it does but contains a label, return false.  If it
1319
/// constant folds return true and set the boolean result in Result.
1320
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1321
                                                   bool &ResultBool,
1322
391k
                                                   bool AllowLabels) {
1323
391k
  llvm::APSInt ResultInt;
1324
391k
  if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1325
360k
    return false;
1326
30.5k
1327
30.5k
  ResultBool = ResultInt.getBoolValue();
1328
30.5k
  return true;
1329
30.5k
}
1330
1331
/// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1332
/// to a constant, or if it does but contains a label, return false.  If it
1333
/// constant folds return true and set the folded value.
1334
bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1335
                                                   llvm::APSInt &ResultInt,
1336
394k
                                                   bool AllowLabels) {
1337
394k
  // FIXME: Rename and handle conversion of other evaluatable things
1338
394k
  // to bool.
1339
394k
  Expr::EvalResult Result;
1340
394k
  if (!Cond->EvaluateAsInt(Result, getContext()))
1341
363k
    return false;  // Not foldable, not integer or not fully evaluatable.
1342
30.9k
1343
30.9k
  llvm::APSInt Int = Result.Val.getInt();
1344
30.9k
  if (!AllowLabels && 
CodeGenFunction::ContainsLabel(Cond)30.9k
)
1345
0
    return false;  // Contains a label.
1346
30.9k
1347
30.9k
  ResultInt = Int;
1348
30.9k
  return true;
1349
30.9k
}
1350
1351
1352
1353
/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1354
/// statement) to the specified blocks.  Based on the condition, this might try
1355
/// to simplify the codegen of the conditional based on the branch.
1356
///
1357
void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1358
                                           llvm::BasicBlock *TrueBlock,
1359
                                           llvm::BasicBlock *FalseBlock,
1360
409k
                                           uint64_t TrueCount) {
1361
409k
  Cond = Cond->IgnoreParens();
1362
409k
1363
409k
  if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1364
225k
1365
225k
    // Handle X && Y in a condition.
1366
225k
    if (CondBOp->getOpcode() == BO_LAnd) {
1367
31.8k
      // If we have "1 && X", simplify the code.  "0 && X" would have constant
1368
31.8k
      // folded if the case was simple enough.
1369
31.8k
      bool ConstantBool = false;
1370
31.8k
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1371
31.8k
          
ConstantBool5.24k
) {
1372
5.24k
        // br(1 && X) -> br(X).
1373
5.24k
        incrementProfileCounter(CondBOp);
1374
5.24k
        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1375
5.24k
                                    TrueCount);
1376
5.24k
      }
1377
26.5k
1378
26.5k
      // If we have "X && 1", simplify the code to use an uncond branch.
1379
26.5k
      // "X && 0" would have been constant folded to 0.
1380
26.5k
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1381
26.5k
          
ConstantBool104
) {
1382
104
        // br(X && 1) -> br(X).
1383
104
        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1384
104
                                    TrueCount);
1385
104
      }
1386
26.4k
1387
26.4k
      // Emit the LHS as a conditional.  If the LHS conditional is false, we
1388
26.4k
      // want to jump to the FalseBlock.
1389
26.4k
      llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1390
26.4k
      // The counter tells us how often we evaluate RHS, and all of TrueCount
1391
26.4k
      // can be propagated to that branch.
1392
26.4k
      uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1393
26.4k
1394
26.4k
      ConditionalEvaluation eval(*this);
1395
26.4k
      {
1396
26.4k
        ApplyDebugLocation DL(*this, Cond);
1397
26.4k
        EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1398
26.4k
        EmitBlock(LHSTrue);
1399
26.4k
      }
1400
26.4k
1401
26.4k
      incrementProfileCounter(CondBOp);
1402
26.4k
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1403
26.4k
1404
26.4k
      // Any temporaries created here are conditional.
1405
26.4k
      eval.begin(*this);
1406
26.4k
      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1407
26.4k
      eval.end(*this);
1408
26.4k
1409
26.4k
      return;
1410
26.4k
    }
1411
193k
1412
193k
    if (CondBOp->getOpcode() == BO_LOr) {
1413
20.0k
      // If we have "0 || X", simplify the code.  "1 || X" would have constant
1414
20.0k
      // folded if the case was simple enough.
1415
20.0k
      bool ConstantBool = false;
1416
20.0k
      if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1417
20.0k
          
!ConstantBool77
) {
1418
77
        // br(0 || X) -> br(X).
1419
77
        incrementProfileCounter(CondBOp);
1420
77
        return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1421
77
                                    TrueCount);
1422
77
      }
1423
19.9k
1424
19.9k
      // If we have "X || 0", simplify the code to use an uncond branch.
1425
19.9k
      // "X || 1" would have been constant folded to 1.
1426
19.9k
      if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1427
19.9k
          
!ConstantBool60
) {
1428
60
        // br(X || 0) -> br(X).
1429
60
        return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1430
60
                                    TrueCount);
1431
60
      }
1432
19.9k
1433
19.9k
      // Emit the LHS as a conditional.  If the LHS conditional is true, we
1434
19.9k
      // want to jump to the TrueBlock.
1435
19.9k
      llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1436
19.9k
      // We have the count for entry to the RHS and for the whole expression
1437
19.9k
      // being true, so we can divy up True count between the short circuit and
1438
19.9k
      // the RHS.
1439
19.9k
      uint64_t LHSCount =
1440
19.9k
          getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1441
19.9k
      uint64_t RHSCount = TrueCount - LHSCount;
1442
19.9k
1443
19.9k
      ConditionalEvaluation eval(*this);
1444
19.9k
      {
1445
19.9k
        ApplyDebugLocation DL(*this, Cond);
1446
19.9k
        EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1447
19.9k
        EmitBlock(LHSFalse);
1448
19.9k
      }
1449
19.9k
1450
19.9k
      incrementProfileCounter(CondBOp);
1451
19.9k
      setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1452
19.9k
1453
19.9k
      // Any temporaries created here are conditional.
1454
19.9k
      eval.begin(*this);
1455
19.9k
      EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1456
19.9k
1457
19.9k
      eval.end(*this);
1458
19.9k
1459
19.9k
      return;
1460
19.9k
    }
1461
193k
  }
1462
357k
1463
357k
  if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1464
38.7k
    // br(!x, t, f) -> br(x, f, t)
1465
38.7k
    if (CondUOp->getOpcode() == UO_LNot) {
1466
38.7k
      // Negate the count.
1467
38.7k
      uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1468
38.7k
      // Negate the condition and swap the destination blocks.
1469
38.7k
      return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1470
38.7k
                                  FalseCount);
1471
38.7k
    }
1472
319k
  }
1473
319k
1474
319k
  if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1475
176
    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1476
176
    llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1477
176
    llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1478
176
1479
176
    ConditionalEvaluation cond(*this);
1480
176
    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1481
176
                         getProfileCount(CondOp));
1482
176
1483
176
    // When computing PGO branch weights, we only know the overall count for
1484
176
    // the true block. This code is essentially doing tail duplication of the
1485
176
    // naive code-gen, introducing new edges for which counts are not
1486
176
    // available. Divide the counts proportionally between the LHS and RHS of
1487
176
    // the conditional operator.
1488
176
    uint64_t LHSScaledTrueCount = 0;
1489
176
    if (TrueCount) {
1490
0
      double LHSRatio =
1491
0
          getProfileCount(CondOp) / (double)getCurrentProfileCount();
1492
0
      LHSScaledTrueCount = TrueCount * LHSRatio;
1493
0
    }
1494
176
1495
176
    cond.begin(*this);
1496
176
    EmitBlock(LHSBlock);
1497
176
    incrementProfileCounter(CondOp);
1498
176
    {
1499
176
      ApplyDebugLocation DL(*this, Cond);
1500
176
      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1501
176
                           LHSScaledTrueCount);
1502
176
    }
1503
176
    cond.end(*this);
1504
176
1505
176
    cond.begin(*this);
1506
176
    EmitBlock(RHSBlock);
1507
176
    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1508
176
                         TrueCount - LHSScaledTrueCount);
1509
176
    cond.end(*this);
1510
176
1511
176
    return;
1512
176
  }
1513
318k
1514
318k
  if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1515
0
    // Conditional operator handling can give us a throw expression as a
1516
0
    // condition for a case like:
1517
0
    //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1518
0
    // Fold this to:
1519
0
    //   br(c, throw x, br(y, t, f))
1520
0
    EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1521
0
    return;
1522
0
  }
1523
318k
1524
318k
  // If the branch has a condition wrapped by __builtin_unpredictable,
1525
318k
  // create metadata that specifies that the branch is unpredictable.
1526
318k
  // Don't bother if not optimizing because that metadata would not be used.
1527
318k
  llvm::MDNode *Unpredictable = nullptr;
1528
318k
  auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1529
318k
  if (Call && 
CGM.getCodeGenOpts().OptimizationLevel != 066.9k
) {
1530
66.5k
    auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1531
66.5k
    if (FD && 
FD->getBuiltinID() == Builtin::BI__builtin_unpredictable66.0k
) {
1532
2
      llvm::MDBuilder MDHelper(getLLVMContext());
1533
2
      Unpredictable = MDHelper.createUnpredictable();
1534
2
    }
1535
66.5k
  }
1536
318k
1537
318k
  // Create branch weights based on the number of times we get here and the
1538
318k
  // number of times the condition should be true.
1539
318k
  uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1540
318k
  llvm::MDNode *Weights =
1541
318k
      createProfileWeights(TrueCount, CurrentCount - TrueCount);
1542
318k
1543
318k
  // Emit the code with the fully general case.
1544
318k
  llvm::Value *CondV;
1545
318k
  {
1546
318k
    ApplyDebugLocation DL(*this, Cond);
1547
318k
    CondV = EvaluateExprAsBool(Cond);
1548
318k
  }
1549
318k
  Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1550
318k
}
1551
1552
/// ErrorUnsupported - Print out an error that codegen doesn't support the
1553
/// specified stmt yet.
1554
1
void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1555
1
  CGM.ErrorUnsupported(S, Type);
1556
1
}
1557
1558
/// emitNonZeroVLAInit - Emit the "zero" initialization of a
1559
/// variable-length array whose elements have a non-zero bit-pattern.
1560
///
1561
/// \param baseType the inner-most element type of the array
1562
/// \param src - a char* pointing to the bit-pattern for a single
1563
/// base element of the array
1564
/// \param sizeInChars - the total size of the VLA, in chars
1565
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1566
                               Address dest, Address src,
1567
0
                               llvm::Value *sizeInChars) {
1568
0
  CGBuilderTy &Builder = CGF.Builder;
1569
0
1570
0
  CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1571
0
  llvm::Value *baseSizeInChars
1572
0
    = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1573
0
1574
0
  Address begin =
1575
0
    Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1576
0
  llvm::Value *end =
1577
0
    Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
1578
0
1579
0
  llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1580
0
  llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1581
0
  llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1582
0
1583
0
  // Make a loop over the VLA.  C99 guarantees that the VLA element
1584
0
  // count must be nonzero.
1585
0
  CGF.EmitBlock(loopBB);
1586
0
1587
0
  llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1588
0
  cur->addIncoming(begin.getPointer(), originBB);
1589
0
1590
0
  CharUnits curAlign =
1591
0
    dest.getAlignment().alignmentOfArrayElement(baseSize);
1592
0
1593
0
  // memcpy the individual element bit-pattern.
1594
0
  Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1595
0
                       /*volatile*/ false);
1596
0
1597
0
  // Go to the next element.
1598
0
  llvm::Value *next =
1599
0
    Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1600
0
1601
0
  // Leave if that's the end of the VLA.
1602
0
  llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1603
0
  Builder.CreateCondBr(done, contBB, loopBB);
1604
0
  cur->addIncoming(next, loopBB);
1605
0
1606
0
  CGF.EmitBlock(contBB);
1607
0
}
1608
1609
void
1610
7.06k
CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1611
7.06k
  // Ignore empty classes in C++.
1612
7.06k
  if (getLangOpts().CPlusPlus) {
1613
6.98k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1614
6.86k
      if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1615
5.91k
        return;
1616
1.15k
    }
1617
6.98k
  }
1618
1.15k
1619
1.15k
  // Cast the dest ptr to the appropriate i8 pointer type.
1620
1.15k
  if (DestPtr.getElementType() != Int8Ty)
1621
1.15k
    DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1622
1.15k
1623
1.15k
  // Get size and alignment info for this aggregate.
1624
1.15k
  CharUnits size = getContext().getTypeSizeInChars(Ty);
1625
1.15k
1626
1.15k
  llvm::Value *SizeVal;
1627
1.15k
  const VariableArrayType *vla;
1628
1.15k
1629
1.15k
  // Don't bother emitting a zero-byte memset.
1630
1.15k
  if (size.isZero()) {
1631
11
    // But note that getTypeInfo returns 0 for a VLA.
1632
11
    if (const VariableArrayType *vlaType =
1633
8
          dyn_cast_or_null<VariableArrayType>(
1634
8
                                          getContext().getAsArrayType(Ty))) {
1635
8
      auto VlaSize = getVLASize(vlaType);
1636
8
      SizeVal = VlaSize.NumElts;
1637
8
      CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1638
8
      if (!eltSize.isOne())
1639
8
        SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1640
8
      vla = vlaType;
1641
8
    } else {
1642
3
      return;
1643
3
    }
1644
1.14k
  } else {
1645
1.14k
    SizeVal = CGM.getSize(size);
1646
1.14k
    vla = nullptr;
1647
1.14k
  }
1648
1.15k
1649
1.15k
  // If the type contains a pointer to data member we can't memset it to zero.
1650
1.15k
  // Instead, create a null constant and copy it to the destination.
1651
1.15k
  // TODO: there are other patterns besides zero that we can usefully memset,
1652
1.15k
  // like -1, which happens to be the pattern used by member-pointers.
1653
1.15k
  
if (1.15k
!CGM.getTypes().isZeroInitializable(Ty)1.15k
) {
1654
9
    // For a VLA, emit a single element, then splat that over the VLA.
1655
9
    if (vla) 
Ty = getContext().getBaseElementType(vla)0
;
1656
9
1657
9
    llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1658
9
1659
9
    llvm::GlobalVariable *NullVariable =
1660
9
      new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1661
9
                               /*isConstant=*/true,
1662
9
                               llvm::GlobalVariable::PrivateLinkage,
1663
9
                               NullConstant, Twine());
1664
9
    CharUnits NullAlign = DestPtr.getAlignment();
1665
9
    NullVariable->setAlignment(NullAlign.getQuantity());
1666
9
    Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1667
9
                   NullAlign);
1668
9
1669
9
    if (vla) 
return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal)0
;
1670
9
1671
9
    // Get and call the appropriate llvm.memcpy overload.
1672
9
    Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1673
9
    return;
1674
9
  }
1675
1.14k
1676
1.14k
  // Otherwise, just memset the whole thing to zero.  This is legal
1677
1.14k
  // because in LLVM, all default initializers (other than the ones we just
1678
1.14k
  // handled above) are guaranteed to have a bit pattern of all zeros.
1679
1.14k
  Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1680
1.14k
}
1681
1682
89
llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1683
89
  // Make sure that there is a block for the indirect goto.
1684
89
  if (!IndirectBranch)
1685
33
    GetIndirectGotoBlock();
1686
89
1687
89
  llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1688
89
1689
89
  // Make sure the indirect branch includes all of the address-taken blocks.
1690
89
  IndirectBranch->addDestination(BB);
1691
89
  return llvm::BlockAddress::get(CurFn, BB);
1692
89
}
1693
1694
87
llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1695
87
  // If we already made the indirect branch for indirect goto, return its block.
1696
87
  if (IndirectBranch) 
return IndirectBranch->getParent()53
;
1697
34
1698
34
  CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1699
34
1700
34
  // Create the PHI node that indirect gotos will add entries to.
1701
34
  llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1702
34
                                              "indirect.goto.dest");
1703
34
1704
34
  // Create the indirect branch instruction.
1705
34
  IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1706
34
  return IndirectBranch->getParent();
1707
34
}
1708
1709
/// Computes the length of an array in elements, as well as the base
1710
/// element type and a properly-typed first element pointer.
1711
llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1712
                                              QualType &baseType,
1713
4.48k
                                              Address &addr) {
1714
4.48k
  const ArrayType *arrayType = origArrayType;
1715
4.48k
1716
4.48k
  // If it's a VLA, we have to load the stored size.  Note that
1717
4.48k
  // this is the size of the VLA in bytes, not its size in elements.
1718
4.48k
  llvm::Value *numVLAElements = nullptr;
1719
4.48k
  if (isa<VariableArrayType>(arrayType)) {
1720
306
    numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
1721
306
1722
306
    // Walk into all VLAs.  This doesn't require changes to addr,
1723
306
    // which has type T* where T is the first non-VLA element type.
1724
343
    do {
1725
343
      QualType elementType = arrayType->getElementType();
1726
343
      arrayType = getContext().getAsArrayType(elementType);
1727
343
1728
343
      // If we only have VLA components, 'addr' requires no adjustment.
1729
343
      if (!arrayType) {
1730
302
        baseType = elementType;
1731
302
        return numVLAElements;
1732
302
      }
1733
41
    } while (isa<VariableArrayType>(arrayType));
1734
306
1735
306
    // We get out here only if we find a constant array type
1736
306
    // inside the VLA.
1737
306
  }
1738
4.48k
1739
4.48k
  // We have some number of constant-length arrays, so addr should
1740
4.48k
  // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1741
4.48k
  // down to the first element of addr.
1742
4.48k
  SmallVector<llvm::Value*, 8> gepIndices;
1743
4.18k
1744
4.18k
  // GEP down to the array type.
1745
4.18k
  llvm::ConstantInt *zero = Builder.getInt32(0);
1746
4.18k
  gepIndices.push_back(zero);
1747
4.18k
1748
4.18k
  uint64_t countFromCLAs = 1;
1749
4.18k
  QualType eltType;
1750
4.18k
1751
4.18k
  llvm::ArrayType *llvmArrayType =
1752
4.18k
    dyn_cast<llvm::ArrayType>(addr.getElementType());
1753
8.23k
  while (llvmArrayType) {
1754
4.05k
    assert(isa<ConstantArrayType>(arrayType));
1755
4.05k
    assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1756
4.05k
             == llvmArrayType->getNumElements());
1757
4.05k
1758
4.05k
    gepIndices.push_back(zero);
1759
4.05k
    countFromCLAs *= llvmArrayType->getNumElements();
1760
4.05k
    eltType = arrayType->getElementType();
1761
4.05k
1762
4.05k
    llvmArrayType =
1763
4.05k
      dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1764
4.05k
    arrayType = getContext().getAsArrayType(arrayType->getElementType());
1765
4.05k
    assert((!llvmArrayType || arrayType) &&
1766
4.05k
           "LLVM and Clang types are out-of-synch");
1767
4.05k
  }
1768
4.18k
1769
4.18k
  if (arrayType) {
1770
229
    // From this point onwards, the Clang array type has been emitted
1771
229
    // as some other type (probably a packed struct). Compute the array
1772
229
    // size, and just emit the 'begin' expression as a bitcast.
1773
498
    while (arrayType) {
1774
269
      countFromCLAs *=
1775
269
          cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1776
269
      eltType = arrayType->getElementType();
1777
269
      arrayType = getContext().getAsArrayType(eltType);
1778
269
    }
1779
229
1780
229
    llvm::Type *baseType = ConvertType(eltType);
1781
229
    addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
1782
3.95k
  } else {
1783
3.95k
    // Create the actual GEP.
1784
3.95k
    addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
1785
3.95k
                                             gepIndices, "array.begin"),
1786
3.95k
                   addr.getAlignment());
1787
3.95k
  }
1788
4.18k
1789
4.18k
  baseType = eltType;
1790
4.18k
1791
4.18k
  llvm::Value *numElements
1792
4.18k
    = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1793
4.18k
1794
4.18k
  // If we had any VLA dimensions, factor them in.
1795
4.18k
  if (numVLAElements)
1796
4
    numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1797
4.18k
1798
4.18k
  return numElements;
1799
4.48k
}
1800
1801
1.85k
CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
1802
1.85k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1803
1.85k
  assert(vla && "type was not a variable array type!");
1804
1.85k
  return getVLASize(vla);
1805
1.85k
}
1806
1807
CodeGenFunction::VlaSizePair
1808
4.19k
CodeGenFunction::getVLASize(const VariableArrayType *type) {
1809
4.19k
  // The number of elements so far; always size_t.
1810
4.19k
  llvm::Value *numElements = nullptr;
1811
4.19k
1812
4.19k
  QualType elementType;
1813
5.15k
  do {
1814
5.15k
    elementType = type->getElementType();
1815
5.15k
    llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1816
5.15k
    assert(vlaSize && "no size for VLA!");
1817
5.15k
    assert(vlaSize->getType() == SizeTy);
1818
5.15k
1819
5.15k
    if (!numElements) {
1820
4.19k
      numElements = vlaSize;
1821
4.19k
    } else {
1822
957
      // It's undefined behavior if this wraps around, so mark it that way.
1823
957
      // FIXME: Teach -fsanitize=undefined to trap this.
1824
957
      numElements = Builder.CreateNUWMul(numElements, vlaSize);
1825
957
    }
1826
5.15k
  } while ((type = getContext().getAsVariableArrayType(elementType)));
1827
4.19k
1828
4.19k
  return { numElements, elementType };
1829
4.19k
}
1830
1831
CodeGenFunction::VlaSizePair
1832
2.55k
CodeGenFunction::getVLAElements1D(QualType type) {
1833
2.55k
  const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1834
2.55k
  assert(vla && "type was not a variable array type!");
1835
2.55k
  return getVLAElements1D(vla);
1836
2.55k
}
1837
1838
CodeGenFunction::VlaSizePair
1839
2.55k
CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
1840
2.55k
  llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
1841
2.55k
  assert(VlaSize && "no size for VLA!");
1842
2.55k
  assert(VlaSize->getType() == SizeTy);
1843
2.55k
  return { VlaSize, Vla->getElementType() };
1844
2.55k
}
1845
1846
2.19k
void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1847
2.19k
  assert(type->isVariablyModifiedType() &&
1848
2.19k
         "Must pass variably modified type to EmitVLASizes!");
1849
2.19k
1850
2.19k
  EnsureInsertPoint();
1851
2.19k
1852
2.19k
  // We're going to walk down into the type and look for VLA
1853
2.19k
  // expressions.
1854
3.03k
  do {
1855
3.03k
    assert(type->isVariablyModifiedType());
1856
3.03k
1857
3.03k
    const Type *ty = type.getTypePtr();
1858
3.03k
    switch (ty->getTypeClass()) {
1859
3.03k
1860
3.03k
#define TYPE(Class, Base)
1861
3.03k
#define ABSTRACT_TYPE(Class, Base)
1862
3.03k
#define NON_CANONICAL_TYPE(Class, Base)
1863
3.03k
#define DEPENDENT_TYPE(Class, Base) 
case Type::Class:0
1864
3.03k
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1865
3.03k
#include "clang/AST/TypeNodes.def"
1866
0
      llvm_unreachable("unexpected dependent type!");
1867
0
1868
0
    // These types are never variably-modified.
1869
0
    case Type::Builtin:
1870
0
    case Type::Complex:
1871
0
    case Type::Vector:
1872
0
    case Type::ExtVector:
1873
0
    case Type::Record:
1874
0
    case Type::Enum:
1875
0
    case Type::Elaborated:
1876
0
    case Type::TemplateSpecialization:
1877
0
    case Type::ObjCTypeParam:
1878
0
    case Type::ObjCObject:
1879
0
    case Type::ObjCInterface:
1880
0
    case Type::ObjCObjectPointer:
1881
0
      llvm_unreachable("type class is never variably-modified!");
1882
0
1883
0
    case Type::Adjusted:
1884
0
      type = cast<AdjustedType>(ty)->getAdjustedType();
1885
0
      break;
1886
0
1887
12
    case Type::Decayed:
1888
12
      type = cast<DecayedType>(ty)->getPointeeType();
1889
12
      break;
1890
0
1891
62
    case Type::Pointer:
1892
62
      type = cast<PointerType>(ty)->getPointeeType();
1893
62
      break;
1894
0
1895
0
    case Type::BlockPointer:
1896
0
      type = cast<BlockPointerType>(ty)->getPointeeType();
1897
0
      break;
1898
0
1899
3
    case Type::LValueReference:
1900
3
    case Type::RValueReference:
1901
3
      type = cast<ReferenceType>(ty)->getPointeeType();
1902
3
      break;
1903
3
1904
3
    case Type::MemberPointer:
1905
0
      type = cast<MemberPointerType>(ty)->getPointeeType();
1906
0
      break;
1907
3
1908
14
    case Type::ConstantArray:
1909
14
    case Type::IncompleteArray:
1910
14
      // Losing element qualification here is fine.
1911
14
      type = cast<ArrayType>(ty)->getElementType();
1912
14
      break;
1913
14
1914
2.86k
    case Type::VariableArray: {
1915
2.86k
      // Losing element qualification here is fine.
1916
2.86k
      const VariableArrayType *vat = cast<VariableArrayType>(ty);
1917
2.86k
1918
2.86k
      // Unknown size indication requires no size computation.
1919
2.86k
      // Otherwise, evaluate and record it.
1920
2.86k
      if (const Expr *size = vat->getSizeExpr()) {
1921
2.86k
        // It's possible that we might have emitted this already,
1922
2.86k
        // e.g. with a typedef and a pointer to it.
1923
2.86k
        llvm::Value *&entry = VLASizeMap[size];
1924
2.86k
        if (!entry) {
1925
2.66k
          llvm::Value *Size = EmitScalarExpr(size);
1926
2.66k
1927
2.66k
          // C11 6.7.6.2p5:
1928
2.66k
          //   If the size is an expression that is not an integer constant
1929
2.66k
          //   expression [...] each time it is evaluated it shall have a value
1930
2.66k
          //   greater than zero.
1931
2.66k
          if (SanOpts.has(SanitizerKind::VLABound) &&
1932
2.66k
              
size->getType()->isSignedIntegerType()2
) {
1933
2
            SanitizerScope SanScope(this);
1934
2
            llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1935
2
            llvm::Constant *StaticArgs[] = {
1936
2
                EmitCheckSourceLocation(size->getBeginLoc()),
1937
2
                EmitCheckTypeDescriptor(size->getType())};
1938
2
            EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
1939
2
                                     SanitizerKind::VLABound),
1940
2
                      SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
1941
2
          }
1942
2.66k
1943
2.66k
          // Always zexting here would be wrong if it weren't
1944
2.66k
          // undefined behavior to have a negative bound.
1945
2.66k
          entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1946
2.66k
        }
1947
2.86k
      }
1948
2.86k
      type = vat->getElementType();
1949
2.86k
      break;
1950
14
    }
1951
14
1952
14
    case Type::FunctionProto:
1953
1
    case Type::FunctionNoProto:
1954
1
      type = cast<FunctionType>(ty)->getReturnType();
1955
1
      break;
1956
1
1957
40
    case Type::Paren:
1958
40
    case Type::TypeOf:
1959
40
    case Type::UnaryTransform:
1960
40
    case Type::Attributed:
1961
40
    case Type::SubstTemplateTypeParm:
1962
40
    case Type::PackExpansion:
1963
40
    case Type::MacroQualified:
1964
40
      // Keep walking after single level desugaring.
1965
40
      type = type.getSingleStepDesugaredType(getContext());
1966
40
      break;
1967
40
1968
40
    case Type::Typedef:
1969
24
    case Type::Decltype:
1970
24
    case Type::Auto:
1971
24
    case Type::DeducedTemplateSpecialization:
1972
24
      // Stop walking: nothing to do.
1973
24
      return;
1974
24
1975
24
    case Type::TypeOfExpr:
1976
13
      // Stop walking: emit typeof expression.
1977
13
      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1978
13
      return;
1979
24
1980
24
    case Type::Atomic:
1981
1
      type = cast<AtomicType>(ty)->getValueType();
1982
1
      break;
1983
24
1984
24
    case Type::Pipe:
1985
0
      type = cast<PipeType>(ty)->getElementType();
1986
0
      break;
1987
3.00k
    }
1988
3.00k
  } while (type->isVariablyModifiedType());
1989
2.19k
}
1990
1991
2.58k
Address CodeGenFunction::EmitVAListRef(const Expr* E) {
1992
2.58k
  if (getContext().getBuiltinVaListType()->isArrayType())
1993
1.01k
    return EmitPointerWithAlignment(E);
1994
1.56k
  return EmitLValue(E).getAddress();
1995
1.56k
}
1996
1997
29
Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
1998
29
  return EmitLValue(E).getAddress();
1999
29
}
2000
2001
void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2002
86.9k
                                              const APValue &Init) {
2003
86.9k
  assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2004
86.9k
  if (CGDebugInfo *Dbg = getDebugInfo())
2005
46.5k
    if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2006
72
      Dbg->EmitGlobalVariable(E->getDecl(), Init);
2007
86.9k
}
2008
2009
CodeGenFunction::PeepholeProtection
2010
886
CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2011
886
  // At the moment, the only aggressive peephole we do in IR gen
2012
886
  // is trunc(zext) folding, but if we add more, we can easily
2013
886
  // extend this protection.
2014
886
2015
886
  if (!rvalue.isScalar()) 
return PeepholeProtection()67
;
2016
819
  llvm::Value *value = rvalue.getScalarVal();
2017
819
  if (!isa<llvm::ZExtInst>(value)) 
return PeepholeProtection()800
;
2018
19
2019
19
  // Just make an extra bitcast.
2020
19
  assert(HaveInsertPoint());
2021
19
  llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2022
19
                                                  Builder.GetInsertBlock());
2023
19
2024
19
  PeepholeProtection protection;
2025
19
  protection.Inst = inst;
2026
19
  return protection;
2027
19
}
2028
2029
886
void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2030
886
  if (!protection.Inst) 
return867
;
2031
19
2032
19
  // In theory, we could try to duplicate the peepholes now, but whatever.
2033
19
  protection.Inst->eraseFromParent();
2034
19
}
2035
2036
void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2037
                                              QualType Ty, SourceLocation Loc,
2038
                                              SourceLocation AssumptionLoc,
2039
                                              llvm::Value *Alignment,
2040
14
                                              llvm::Value *OffsetValue) {
2041
14
  llvm::Value *TheCheck;
2042
14
  llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2043
14
      CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
2044
14
  if (SanOpts.has(SanitizerKind::Alignment)) {
2045
6
    EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2046
6
                                 OffsetValue, TheCheck, Assumption);
2047
6
  }
2048
14
}
2049
2050
void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2051
                                              QualType Ty, SourceLocation Loc,
2052
                                              SourceLocation AssumptionLoc,
2053
                                              unsigned Alignment,
2054
342
                                              llvm::Value *OffsetValue) {
2055
342
  llvm::Value *TheCheck;
2056
342
  llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2057
342
      CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
2058
342
  if (SanOpts.has(SanitizerKind::Alignment)) {
2059
27
    llvm::Value *AlignmentVal = llvm::ConstantInt::get(IntPtrTy, Alignment);
2060
27
    EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, AlignmentVal,
2061
27
                                 OffsetValue, TheCheck, Assumption);
2062
27
  }
2063
342
}
2064
2065
void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
2066
                                              const Expr *E,
2067
                                              SourceLocation AssumptionLoc,
2068
                                              unsigned Alignment,
2069
332
                                              llvm::Value *OffsetValue) {
2070
332
  if (auto *CE = dyn_cast<CastExpr>(E))
2071
139
    E = CE->getSubExprAsWritten();
2072
332
  QualType Ty = E->getType();
2073
332
  SourceLocation Loc = E->getExprLoc();
2074
332
2075
332
  EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2076
332
                          OffsetValue);
2077
332
}
2078
2079
llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2080
                                                 llvm::Value *AnnotatedVal,
2081
                                                 StringRef AnnotationStr,
2082
22
                                                 SourceLocation Location) {
2083
22
  llvm::Value *Args[4] = {
2084
22
    AnnotatedVal,
2085
22
    Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2086
22
    Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2087
22
    CGM.EmitAnnotationLineNo(Location)
2088
22
  };
2089
22
  return Builder.CreateCall(AnnotationFn, Args);
2090
22
}
2091
2092
7
void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2093
7
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2094
7
  // FIXME We create a new bitcast for every annotation because that's what
2095
7
  // llvm-gcc was doing.
2096
7
  for (const auto *I : D->specific_attrs<AnnotateAttr>())
2097
11
    EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2098
11
                       Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2099
11
                       I->getAnnotation(), D->getLocation());
2100
7
}
2101
2102
Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2103
2
                                              Address Addr) {
2104
2
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2105
2
  llvm::Value *V = Addr.getPointer();
2106
2
  llvm::Type *VTy = V->getType();
2107
2
  llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2108
2
                                    CGM.Int8PtrTy);
2109
2
2110
4
  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2111
4
    // FIXME Always emit the cast inst so we can differentiate between
2112
4
    // annotation on the first field of a struct and annotation on the struct
2113
4
    // itself.
2114
4
    if (VTy != CGM.Int8PtrTy)
2115
4
      V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
2116
4
    V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
2117
4
    V = Builder.CreateBitCast(V, VTy);
2118
4
  }
2119
2
2120
2
  return Address(V, Addr.getAlignment());
2121
2
}
2122
2123
40.0k
CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2124
2125
CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2126
50.6k
    : CGF(CGF) {
2127
50.6k
  assert(!CGF->IsSanitizerScope);
2128
50.6k
  CGF->IsSanitizerScope = true;
2129
50.6k
}
2130
2131
50.6k
CodeGenFunction::SanitizerScope::~SanitizerScope() {
2132
50.6k
  CGF->IsSanitizerScope = false;
2133
50.6k
}
2134
2135
void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2136
                                   const llvm::Twine &Name,
2137
                                   llvm::BasicBlock *BB,
2138
11.9M
                                   llvm::BasicBlock::iterator InsertPt) const {
2139
11.9M
  LoopStack.InsertHelper(I);
2140
11.9M
  if (IsSanitizerScope)
2141
11.4k
    CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2142
11.9M
}
2143
2144
void CGBuilderInserter::InsertHelper(
2145
    llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2146
11.9M
    llvm::BasicBlock::iterator InsertPt) const {
2147
11.9M
  llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2148
11.9M
  if (CGF)
2149
11.9M
    CGF->InsertHelper(I, Name, BB, InsertPt);
2150
11.9M
}
2151
2152
static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
2153
                                CodeGenModule &CGM, const FunctionDecl *FD,
2154
26.7k
                                std::string &FirstMissing) {
2155
26.7k
  // If there aren't any required features listed then go ahead and return.
2156
26.7k
  if (ReqFeatures.empty())
2157
0
    return false;
2158
26.7k
2159
26.7k
  // Now build up the set of caller features and verify that all the required
2160
26.7k
  // features are there.
2161
26.7k
  llvm::StringMap<bool> CallerFeatureMap;
2162
26.7k
  CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
2163
26.7k
2164
26.7k
  // If we have at least one of the features in the feature list return
2165
26.7k
  // true, otherwise return false.
2166
26.7k
  return std::all_of(
2167
212k
      ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
2168
212k
        SmallVector<StringRef, 1> OrFeatures;
2169
212k
        Feature.split(OrFeatures, '|');
2170
213k
        return llvm::any_of(OrFeatures, [&](StringRef Feature) {
2171
213k
          if (!CallerFeatureMap.lookup(Feature)) {
2172
2.20k
            FirstMissing = Feature.str();
2173
2.20k
            return false;
2174
2.20k
          }
2175
211k
          return true;
2176
211k
        });
2177
212k
      });
2178
26.7k
}
2179
2180
// Emits an error if we don't have a valid set of target features for the
2181
// called function.
2182
void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2183
35.4k
                                          const FunctionDecl *TargetDecl) {
2184
35.4k
  return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2185
35.4k
}
2186
2187
// Emits an error if we don't have a valid set of target features for the
2188
// called function.
2189
void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2190
47.1k
                                          const FunctionDecl *TargetDecl) {
2191
47.1k
  // Early exit if this is an indirect call.
2192
47.1k
  if (!TargetDecl)
2193
0
    return;
2194
47.1k
2195
47.1k
  // Get the current enclosing function if it exists. If it doesn't
2196
47.1k
  // we can't check the target features anyhow.
2197
47.1k
  const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
2198
47.1k
  if (!FD)
2199
0
    return;
2200
47.1k
2201
47.1k
  // Grab the required features for the call. For a builtin this is listed in
2202
47.1k
  // the td file with the default cpu, for an always_inline function this is any
2203
47.1k
  // listed cpu and any listed features.
2204
47.1k
  unsigned BuiltinID = TargetDecl->getBuiltinID();
2205
47.1k
  std::string MissingFeature;
2206
47.1k
  if (BuiltinID) {
2207
35.4k
    SmallVector<StringRef, 1> ReqFeatures;
2208
35.4k
    const char *FeatureList =
2209
35.4k
        CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2210
35.4k
    // Return if the builtin doesn't have any required features.
2211
35.4k
    if (!FeatureList || 
StringRef(FeatureList) == ""15.3k
)
2212
20.4k
      return;
2213
14.9k
    StringRef(FeatureList).split(ReqFeatures, ',');
2214
14.9k
    if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2215
528
      CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2216
528
          << TargetDecl->getDeclName()
2217
528
          << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
2218
14.9k
2219
14.9k
  } else 
if (11.7k
TargetDecl->hasAttr<TargetAttr>()11.7k
||
2220
11.7k
             
TargetDecl->hasAttr<CPUSpecificAttr>()0
) {
2221
11.7k
    // Get the required features for the callee.
2222
11.7k
2223
11.7k
    const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2224
11.7k
    TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
2225
11.7k
2226
11.7k
    SmallVector<StringRef, 1> ReqFeatures;
2227
11.7k
    llvm::StringMap<bool> CalleeFeatureMap;
2228
11.7k
    CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2229
11.7k
2230
13.0k
    for (const auto &F : ParsedAttr.Features) {
2231
13.0k
      if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2232
13.0k
        ReqFeatures.push_back(StringRef(F).substr(1));
2233
13.0k
    }
2234
11.7k
2235
182k
    for (const auto &F : CalleeFeatureMap) {
2236
182k
      // Only positive features are "required".
2237
182k
      if (F.getValue())
2238
182k
        ReqFeatures.push_back(F.getKey());
2239
182k
    }
2240
11.7k
    if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
2241
5
      CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2242
5
          << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2243
11.7k
  }
2244
47.1k
}
2245
2246
84
void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2247
84
  if (!CGM.getCodeGenOpts().SanitizeStats)
2248
74
    return;
2249
10
2250
10
  llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2251
10
  IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2252
10
  CGM.getSanStats().create(IRB, SSK);
2253
10
}
2254
2255
llvm::Value *
2256
212
CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2257
212
  llvm::Value *Condition = nullptr;
2258
212
2259
212
  if (!RO.Conditions.Architecture.empty())
2260
68
    Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2261
212
2262
212
  if (!RO.Conditions.Features.empty()) {
2263
91
    llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2264
91
    Condition =
2265
91
        Condition ? 
Builder.CreateAnd(Condition, FeatureCond)2
:
FeatureCond89
;
2266
91
  }
2267
212
  return Condition;
2268
212
}
2269
2270
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2271
                                             llvm::Function *Resolver,
2272
                                             CGBuilderTy &Builder,
2273
                                             llvm::Function *FuncToReturn,
2274
212
                                             bool SupportsIFunc) {
2275
212
  if (SupportsIFunc) {
2276
104
    Builder.CreateRet(FuncToReturn);
2277
104
    return;
2278
104
  }
2279
108
2280
108
  llvm::SmallVector<llvm::Value *, 10> Args;
2281
108
  llvm::for_each(Resolver->args(),
2282
116
                 [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2283
108
2284
108
  llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2285
108
  Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2286
108
2287
108
  if (Resolver->getReturnType()->isVoidTy())
2288
29
    Builder.CreateRetVoid();
2289
79
  else
2290
79
    Builder.CreateRet(Result);
2291
108
}
2292
2293
void CodeGenFunction::EmitMultiVersionResolver(
2294
65
    llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2295
65
  assert((getContext().getTargetInfo().getTriple().getArch() ==
2296
65
              llvm::Triple::x86 ||
2297
65
          getContext().getTargetInfo().getTriple().getArch() ==
2298
65
              llvm::Triple::x86_64) &&
2299
65
         "Only implemented for x86 targets");
2300
65
2301
65
  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2302
65
2303
65
  // Main function's basic block.
2304
65
  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2305
65
  Builder.SetInsertPoint(CurBlock);
2306
65
  EmitX86CpuInit();
2307
65
2308
212
  for (const MultiVersionResolverOption &RO : Options) {
2309
212
    Builder.SetInsertPoint(CurBlock);
2310
212
    llvm::Value *Condition = FormResolverCondition(RO);
2311
212
2312
212
    // The 'default' or 'generic' case.
2313
212
    if (!Condition) {
2314
55
      assert(&RO == Options.end() - 1 &&
2315
55
             "Default or Generic case must be last");
2316
55
      CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2317
55
                                       SupportsIFunc);
2318
55
      return;
2319
55
    }
2320
157
2321
157
    llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2322
157
    CGBuilderTy RetBuilder(*this, RetBlock);
2323
157
    CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2324
157
                                     SupportsIFunc);
2325
157
    CurBlock = createBasicBlock("resolver_else", Resolver);
2326
157
    Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2327
157
  }
2328
65
2329
65
  // If no generic/default, emit an unreachable.
2330
65
  Builder.SetInsertPoint(CurBlock);
2331
10
  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2332
10
  TrapCall->setDoesNotReturn();
2333
10
  TrapCall->setDoesNotThrow();
2334
10
  Builder.CreateUnreachable();
2335
10
  Builder.ClearInsertionPoint();
2336
10
}
2337
2338
// Loc - where the diagnostic will point, where in the source code this
2339
//  alignment has failed.
2340
// SecondaryLoc - if present (will be present if sufficiently different from
2341
//  Loc), the diagnostic will additionally point a "Note:" to this location.
2342
//  It should be the location where the __attribute__((assume_aligned))
2343
//  was written e.g.
2344
void CodeGenFunction::EmitAlignmentAssumptionCheck(
2345
    llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2346
    SourceLocation SecondaryLoc, llvm::Value *Alignment,
2347
    llvm::Value *OffsetValue, llvm::Value *TheCheck,
2348
33
    llvm::Instruction *Assumption) {
2349
33
  assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2350
33
         cast<llvm::CallInst>(Assumption)->getCalledValue() ==
2351
33
             llvm::Intrinsic::getDeclaration(
2352
33
                 Builder.GetInsertBlock()->getParent()->getParent(),
2353
33
                 llvm::Intrinsic::assume) &&
2354
33
         "Assumption should be a call to llvm.assume().");
2355
33
  assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2356
33
         "Assumption should be the last instruction of the basic block, "
2357
33
         "since the basic block is still being generated.");
2358
33
2359
33
  if (!SanOpts.has(SanitizerKind::Alignment))
2360
0
    return;
2361
33
2362
33
  // Don't check pointers to volatile data. The behavior here is implementation-
2363
33
  // defined.
2364
33
  if (Ty->getPointeeType().isVolatileQualified())
2365
1
    return;
2366
32
2367
32
  // We need to temorairly remove the assumption so we can insert the
2368
32
  // sanitizer check before it, else the check will be dropped by optimizations.
2369
32
  Assumption->removeFromParent();
2370
32
2371
32
  {
2372
32
    SanitizerScope SanScope(this);
2373
32
2374
32
    if (!OffsetValue)
2375
23
      OffsetValue = Builder.getInt1(0); // no offset.
2376
32
2377
32
    llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2378
32
                                    EmitCheckSourceLocation(SecondaryLoc),
2379
32
                                    EmitCheckTypeDescriptor(Ty)};
2380
32
    llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2381
32
                                  EmitCheckValue(Alignment),
2382
32
                                  EmitCheckValue(OffsetValue)};
2383
32
    EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2384
32
              SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2385
32
  }
2386
32
2387
32
  // We are now in the (new, empty) "cont" basic block.
2388
32
  // Reintroduce the assumption.
2389
32
  Builder.Insert(Assumption);
2390
32
  // FIXME: Assumption still has it's original basic block as it's Parent.
2391
32
}
2392
2393
166k
llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2394
166k
  if (CGDebugInfo *DI = getDebugInfo())
2395
72.2k
    return DI->SourceLocToDebugLoc(Location);
2396
94.3k
2397
94.3k
  return llvm::DebugLoc();
2398
94.3k
}