1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGBlocks.h" 16 #include "CGCleanup.h" 17 #include "CGCUDARuntime.h" 18 #include "CGCXXABI.h" 19 #include "CGDebugInfo.h" 20 #include "CGOpenMPRuntime.h" 21 #include "CodeGenModule.h" 22 #include "CodeGenPGO.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/Decl.h" 26 #include "clang/AST/DeclCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/CodeGen/CGFunctionInfo.h" 31 #include "clang/Frontend/CodeGenOptions.h" 32 #include "clang/Sema/SemaDiagnostic.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/MDBuilder.h" 36 #include "llvm/IR/Operator.h" 37 using namespace clang; 38 using namespace CodeGen; 39 40 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 41 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 42 Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 43 CGBuilderInserterTy(this)), 44 CurFn(nullptr), ReturnValue(Address::invalid()), 45 CapturedStmtInfo(nullptr), 46 SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false), 47 CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false), 48 IsOutlinedSEHHelper(false), 49 BlockInfo(nullptr), BlockPointer(nullptr), 50 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr), 51 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr), 52 ExceptionSlot(nullptr), EHSelectorSlot(nullptr), 53 DebugInfo(CGM.getModuleDebugInfo()), 54 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 55 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 56 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 57 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 58 CXXABIThisValue(nullptr), CXXThisValue(nullptr), 59 CXXStructorImplicitParamDecl(nullptr), 60 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 61 CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 62 TerminateHandler(nullptr), TrapBB(nullptr) { 63 if (!suppressNewContext) 64 CGM.getCXXABI().getMangleContext().startNewFunction(); 65 66 llvm::FastMathFlags FMF; 67 if (CGM.getLangOpts().FastMath) 68 FMF.setUnsafeAlgebra(); 69 if (CGM.getLangOpts().FiniteMathOnly) { 70 FMF.setNoNaNs(); 71 FMF.setNoInfs(); 72 } 73 if (CGM.getCodeGenOpts().NoNaNsFPMath) { 74 FMF.setNoNaNs(); 75 } 76 if (CGM.getCodeGenOpts().NoSignedZeros) { 77 FMF.setNoSignedZeros(); 78 } 79 if (CGM.getCodeGenOpts().ReciprocalMath) { 80 FMF.setAllowReciprocal(); 81 } 82 Builder.setFastMathFlags(FMF); 83 } 84 85 CodeGenFunction::~CodeGenFunction() { 86 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 87 88 // If there are any unclaimed block infos, go ahead and destroy them 89 // now. This can happen if IR-gen gets clever and skips evaluating 90 // something. 91 if (FirstBlockInfo) 92 destroyBlockInfos(FirstBlockInfo); 93 94 if (getLangOpts().OpenMP) { 95 CGM.getOpenMPRuntime().functionFinished(*this); 96 } 97 } 98 99 CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T, 100 AlignmentSource *Source) { 101 return getNaturalTypeAlignment(T->getPointeeType(), Source, 102 /*forPointee*/ true); 103 } 104 105 CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T, 106 AlignmentSource *Source, 107 bool forPointeeType) { 108 // Honor alignment typedef attributes even on incomplete types. 109 // We also honor them straight for C++ class types, even as pointees; 110 // there's an expressivity gap here. 111 if (auto TT = T->getAs<TypedefType>()) { 112 if (auto Align = TT->getDecl()->getMaxAlignment()) { 113 if (Source) *Source = AlignmentSource::AttributedType; 114 return getContext().toCharUnitsFromBits(Align); 115 } 116 } 117 118 if (Source) *Source = AlignmentSource::Type; 119 120 CharUnits Alignment; 121 if (T->isIncompleteType()) { 122 Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best. 123 } else { 124 // For C++ class pointees, we don't know whether we're pointing at a 125 // base or a complete object, so we generally need to use the 126 // non-virtual alignment. 127 const CXXRecordDecl *RD; 128 if (forPointeeType && (RD = T->getAsCXXRecordDecl())) { 129 Alignment = CGM.getClassPointerAlignment(RD); 130 } else { 131 Alignment = getContext().getTypeAlignInChars(T); 132 } 133 134 // Cap to the global maximum type alignment unless the alignment 135 // was somehow explicit on the type. 136 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 137 if (Alignment.getQuantity() > MaxAlign && 138 !getContext().isAlignmentRequired(T)) 139 Alignment = CharUnits::fromQuantity(MaxAlign); 140 } 141 } 142 return Alignment; 143 } 144 145 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 146 AlignmentSource AlignSource; 147 CharUnits Alignment = getNaturalTypeAlignment(T, &AlignSource); 148 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), AlignSource, 149 CGM.getTBAAInfo(T)); 150 } 151 152 /// Given a value of type T* that may not be to a complete object, 153 /// construct an l-value with the natural pointee alignment of T. 154 LValue 155 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 156 AlignmentSource AlignSource; 157 CharUnits Align = getNaturalTypeAlignment(T, &AlignSource, /*pointee*/ true); 158 return MakeAddrLValue(Address(V, Align), T, AlignSource); 159 } 160 161 162 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 163 return CGM.getTypes().ConvertTypeForMem(T); 164 } 165 166 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 167 return CGM.getTypes().ConvertType(T); 168 } 169 170 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 171 type = type.getCanonicalType(); 172 while (true) { 173 switch (type->getTypeClass()) { 174 #define TYPE(name, parent) 175 #define ABSTRACT_TYPE(name, parent) 176 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 177 #define DEPENDENT_TYPE(name, parent) case Type::name: 178 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 179 #include "clang/AST/TypeNodes.def" 180 llvm_unreachable("non-canonical or dependent type in IR-generation"); 181 182 case Type::Auto: 183 llvm_unreachable("undeduced auto type in IR-generation"); 184 185 // Various scalar types. 186 case Type::Builtin: 187 case Type::Pointer: 188 case Type::BlockPointer: 189 case Type::LValueReference: 190 case Type::RValueReference: 191 case Type::MemberPointer: 192 case Type::Vector: 193 case Type::ExtVector: 194 case Type::FunctionProto: 195 case Type::FunctionNoProto: 196 case Type::Enum: 197 case Type::ObjCObjectPointer: 198 case Type::Pipe: 199 return TEK_Scalar; 200 201 // Complexes. 202 case Type::Complex: 203 return TEK_Complex; 204 205 // Arrays, records, and Objective-C objects. 206 case Type::ConstantArray: 207 case Type::IncompleteArray: 208 case Type::VariableArray: 209 case Type::Record: 210 case Type::ObjCObject: 211 case Type::ObjCInterface: 212 return TEK_Aggregate; 213 214 // We operate on atomic values according to their underlying type. 215 case Type::Atomic: 216 type = cast<AtomicType>(type)->getValueType(); 217 continue; 218 } 219 llvm_unreachable("unknown type kind!"); 220 } 221 } 222 223 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 224 // For cleanliness, we try to avoid emitting the return block for 225 // simple cases. 226 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 227 228 if (CurBB) { 229 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 230 231 // We have a valid insert point, reuse it if it is empty or there are no 232 // explicit jumps to the return block. 233 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 234 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 235 delete ReturnBlock.getBlock(); 236 } else 237 EmitBlock(ReturnBlock.getBlock()); 238 return llvm::DebugLoc(); 239 } 240 241 // Otherwise, if the return block is the target of a single direct 242 // branch then we can just put the code in that block instead. This 243 // cleans up functions which started with a unified return block. 244 if (ReturnBlock.getBlock()->hasOneUse()) { 245 llvm::BranchInst *BI = 246 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 247 if (BI && BI->isUnconditional() && 248 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 249 // Record/return the DebugLoc of the simple 'return' expression to be used 250 // later by the actual 'ret' instruction. 251 llvm::DebugLoc Loc = BI->getDebugLoc(); 252 Builder.SetInsertPoint(BI->getParent()); 253 BI->eraseFromParent(); 254 delete ReturnBlock.getBlock(); 255 return Loc; 256 } 257 } 258 259 // FIXME: We are at an unreachable point, there is no reason to emit the block 260 // unless it has uses. However, we still need a place to put the debug 261 // region.end for now. 262 263 EmitBlock(ReturnBlock.getBlock()); 264 return llvm::DebugLoc(); 265 } 266 267 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 268 if (!BB) return; 269 if (!BB->use_empty()) 270 return CGF.CurFn->getBasicBlockList().push_back(BB); 271 delete BB; 272 } 273 274 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 275 assert(BreakContinueStack.empty() && 276 "mismatched push/pop in break/continue stack!"); 277 278 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 279 && NumSimpleReturnExprs == NumReturnExprs 280 && ReturnBlock.getBlock()->use_empty(); 281 // Usually the return expression is evaluated before the cleanup 282 // code. If the function contains only a simple return statement, 283 // such as a constant, the location before the cleanup code becomes 284 // the last useful breakpoint in the function, because the simple 285 // return expression will be evaluated after the cleanup code. To be 286 // safe, set the debug location for cleanup code to the location of 287 // the return statement. Otherwise the cleanup code should be at the 288 // end of the function's lexical scope. 289 // 290 // If there are multiple branches to the return block, the branch 291 // instructions will get the location of the return statements and 292 // all will be fine. 293 if (CGDebugInfo *DI = getDebugInfo()) { 294 if (OnlySimpleReturnStmts) 295 DI->EmitLocation(Builder, LastStopPoint); 296 else 297 DI->EmitLocation(Builder, EndLoc); 298 } 299 300 // Pop any cleanups that might have been associated with the 301 // parameters. Do this in whatever block we're currently in; it's 302 // important to do this before we enter the return block or return 303 // edges will be *really* confused. 304 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 305 bool HasOnlyLifetimeMarkers = 306 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 307 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 308 if (HasCleanups) { 309 // Make sure the line table doesn't jump back into the body for 310 // the ret after it's been at EndLoc. 311 if (CGDebugInfo *DI = getDebugInfo()) 312 if (OnlySimpleReturnStmts) 313 DI->EmitLocation(Builder, EndLoc); 314 315 PopCleanupBlocks(PrologueCleanupDepth); 316 } 317 318 // Emit function epilog (to return). 319 llvm::DebugLoc Loc = EmitReturnBlock(); 320 321 if (ShouldInstrumentFunction()) 322 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 323 324 // Emit debug descriptor for function end. 325 if (CGDebugInfo *DI = getDebugInfo()) 326 DI->EmitFunctionEnd(Builder); 327 328 // Reset the debug location to that of the simple 'return' expression, if any 329 // rather than that of the end of the function's scope '}'. 330 ApplyDebugLocation AL(*this, Loc); 331 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 332 EmitEndEHSpec(CurCodeDecl); 333 334 assert(EHStack.empty() && 335 "did not remove all scopes from cleanup stack!"); 336 337 // If someone did an indirect goto, emit the indirect goto block at the end of 338 // the function. 339 if (IndirectBranch) { 340 EmitBlock(IndirectBranch->getParent()); 341 Builder.ClearInsertionPoint(); 342 } 343 344 // If some of our locals escaped, insert a call to llvm.localescape in the 345 // entry block. 346 if (!EscapedLocals.empty()) { 347 // Invert the map from local to index into a simple vector. There should be 348 // no holes. 349 SmallVector<llvm::Value *, 4> EscapeArgs; 350 EscapeArgs.resize(EscapedLocals.size()); 351 for (auto &Pair : EscapedLocals) 352 EscapeArgs[Pair.second] = Pair.first; 353 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 354 &CGM.getModule(), llvm::Intrinsic::localescape); 355 CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 356 } 357 358 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 359 llvm::Instruction *Ptr = AllocaInsertPt; 360 AllocaInsertPt = nullptr; 361 Ptr->eraseFromParent(); 362 363 // If someone took the address of a label but never did an indirect goto, we 364 // made a zero entry PHI node, which is illegal, zap it now. 365 if (IndirectBranch) { 366 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 367 if (PN->getNumIncomingValues() == 0) { 368 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 369 PN->eraseFromParent(); 370 } 371 } 372 373 EmitIfUsed(*this, EHResumeBlock); 374 EmitIfUsed(*this, TerminateLandingPad); 375 EmitIfUsed(*this, TerminateHandler); 376 EmitIfUsed(*this, UnreachableBlock); 377 378 if (CGM.getCodeGenOpts().EmitDeclMetadata) 379 EmitDeclMetadata(); 380 381 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 382 I = DeferredReplacements.begin(), 383 E = DeferredReplacements.end(); 384 I != E; ++I) { 385 I->first->replaceAllUsesWith(I->second); 386 I->first->eraseFromParent(); 387 } 388 } 389 390 /// ShouldInstrumentFunction - Return true if the current function should be 391 /// instrumented with __cyg_profile_func_* calls 392 bool CodeGenFunction::ShouldInstrumentFunction() { 393 if (!CGM.getCodeGenOpts().InstrumentFunctions) 394 return false; 395 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 396 return false; 397 return true; 398 } 399 400 /// ShouldXRayInstrument - Return true if the current function should be 401 /// instrumented with XRay nop sleds. 402 bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 403 return CGM.getCodeGenOpts().XRayInstrumentFunctions; 404 } 405 406 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 407 /// instrumentation function with the current function and the call site, if 408 /// function instrumentation is enabled. 409 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 410 auto NL = ApplyDebugLocation::CreateArtificial(*this); 411 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 412 llvm::PointerType *PointerTy = Int8PtrTy; 413 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 414 llvm::FunctionType *FunctionTy = 415 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 416 417 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 418 llvm::CallInst *CallSite = Builder.CreateCall( 419 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 420 llvm::ConstantInt::get(Int32Ty, 0), 421 "callsite"); 422 423 llvm::Value *args[] = { 424 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 425 CallSite 426 }; 427 428 EmitNounwindRuntimeCall(F, args); 429 } 430 431 static void removeImageAccessQualifier(std::string& TyName) { 432 std::string ReadOnlyQual("__read_only"); 433 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 434 if (ReadOnlyPos != std::string::npos) 435 // "+ 1" for the space after access qualifier. 436 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 437 else { 438 std::string WriteOnlyQual("__write_only"); 439 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 440 if (WriteOnlyPos != std::string::npos) 441 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 442 else { 443 std::string ReadWriteQual("__read_write"); 444 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 445 if (ReadWritePos != std::string::npos) 446 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 447 } 448 } 449 } 450 451 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 452 // information in the program executable. The argument information stored 453 // includes the argument name, its type, the address and access qualifiers used. 454 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 455 CodeGenModule &CGM, llvm::LLVMContext &Context, 456 CGBuilderTy &Builder, ASTContext &ASTCtx) { 457 // Create MDNodes that represent the kernel arg metadata. 458 // Each MDNode is a list in the form of "key", N number of values which is 459 // the same number of values as their are kernel arguments. 460 461 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 462 463 // MDNode for the kernel argument address space qualifiers. 464 SmallVector<llvm::Metadata *, 8> addressQuals; 465 466 // MDNode for the kernel argument access qualifiers (images only). 467 SmallVector<llvm::Metadata *, 8> accessQuals; 468 469 // MDNode for the kernel argument type names. 470 SmallVector<llvm::Metadata *, 8> argTypeNames; 471 472 // MDNode for the kernel argument base type names. 473 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 474 475 // MDNode for the kernel argument type qualifiers. 476 SmallVector<llvm::Metadata *, 8> argTypeQuals; 477 478 // MDNode for the kernel argument names. 479 SmallVector<llvm::Metadata *, 8> argNames; 480 481 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 482 const ParmVarDecl *parm = FD->getParamDecl(i); 483 QualType ty = parm->getType(); 484 std::string typeQuals; 485 486 if (ty->isPointerType()) { 487 QualType pointeeTy = ty->getPointeeType(); 488 489 // Get address qualifier. 490 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32( 491 ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace())))); 492 493 // Get argument type name. 494 std::string typeName = 495 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 496 497 // Turn "unsigned type" to "utype" 498 std::string::size_type pos = typeName.find("unsigned"); 499 if (pointeeTy.isCanonical() && pos != std::string::npos) 500 typeName.erase(pos+1, 8); 501 502 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 503 504 std::string baseTypeName = 505 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 506 Policy) + 507 "*"; 508 509 // Turn "unsigned type" to "utype" 510 pos = baseTypeName.find("unsigned"); 511 if (pos != std::string::npos) 512 baseTypeName.erase(pos+1, 8); 513 514 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 515 516 // Get argument type qualifiers: 517 if (ty.isRestrictQualified()) 518 typeQuals = "restrict"; 519 if (pointeeTy.isConstQualified() || 520 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 521 typeQuals += typeQuals.empty() ? "const" : " const"; 522 if (pointeeTy.isVolatileQualified()) 523 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 524 } else { 525 uint32_t AddrSpc = 0; 526 bool isPipe = ty->isPipeType(); 527 if (ty->isImageType() || isPipe) 528 AddrSpc = 529 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global); 530 531 addressQuals.push_back( 532 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc))); 533 534 // Get argument type name. 535 std::string typeName; 536 if (isPipe) 537 typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType() 538 .getAsString(Policy); 539 else 540 typeName = ty.getUnqualifiedType().getAsString(Policy); 541 542 // Turn "unsigned type" to "utype" 543 std::string::size_type pos = typeName.find("unsigned"); 544 if (ty.isCanonical() && pos != std::string::npos) 545 typeName.erase(pos+1, 8); 546 547 std::string baseTypeName; 548 if (isPipe) 549 baseTypeName = ty.getCanonicalType()->getAs<PipeType>() 550 ->getElementType().getCanonicalType() 551 .getAsString(Policy); 552 else 553 baseTypeName = 554 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 555 556 // Remove access qualifiers on images 557 // (as they are inseparable from type in clang implementation, 558 // but OpenCL spec provides a special query to get access qualifier 559 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 560 if (ty->isImageType()) { 561 removeImageAccessQualifier(typeName); 562 removeImageAccessQualifier(baseTypeName); 563 } 564 565 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 566 567 // Turn "unsigned type" to "utype" 568 pos = baseTypeName.find("unsigned"); 569 if (pos != std::string::npos) 570 baseTypeName.erase(pos+1, 8); 571 572 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 573 574 // Get argument type qualifiers: 575 if (ty.isConstQualified()) 576 typeQuals = "const"; 577 if (ty.isVolatileQualified()) 578 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 579 if (isPipe) 580 typeQuals = "pipe"; 581 } 582 583 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 584 585 // Get image and pipe access qualifier: 586 if (ty->isImageType()|| ty->isPipeType()) { 587 const OpenCLAccessAttr *A = parm->getAttr<OpenCLAccessAttr>(); 588 if (A && A->isWriteOnly()) 589 accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 590 else if (A && A->isReadWrite()) 591 accessQuals.push_back(llvm::MDString::get(Context, "read_write")); 592 else 593 accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 594 } else 595 accessQuals.push_back(llvm::MDString::get(Context, "none")); 596 597 // Get argument name. 598 argNames.push_back(llvm::MDString::get(Context, parm->getName())); 599 } 600 601 Fn->setMetadata("kernel_arg_addr_space", 602 llvm::MDNode::get(Context, addressQuals)); 603 Fn->setMetadata("kernel_arg_access_qual", 604 llvm::MDNode::get(Context, accessQuals)); 605 Fn->setMetadata("kernel_arg_type", 606 llvm::MDNode::get(Context, argTypeNames)); 607 Fn->setMetadata("kernel_arg_base_type", 608 llvm::MDNode::get(Context, argBaseTypeNames)); 609 Fn->setMetadata("kernel_arg_type_qual", 610 llvm::MDNode::get(Context, argTypeQuals)); 611 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 612 Fn->setMetadata("kernel_arg_name", 613 llvm::MDNode::get(Context, argNames)); 614 } 615 616 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 617 llvm::Function *Fn) 618 { 619 if (!FD->hasAttr<OpenCLKernelAttr>()) 620 return; 621 622 llvm::LLVMContext &Context = getLLVMContext(); 623 624 GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext()); 625 626 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 627 QualType hintQTy = A->getTypeHint(); 628 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 629 bool isSignedInteger = 630 hintQTy->isSignedIntegerType() || 631 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 632 llvm::Metadata *attrMDArgs[] = { 633 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 634 CGM.getTypes().ConvertType(A->getTypeHint()))), 635 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 636 llvm::IntegerType::get(Context, 32), 637 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))}; 638 Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, attrMDArgs)); 639 } 640 641 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 642 llvm::Metadata *attrMDArgs[] = { 643 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 644 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 645 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 646 Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, attrMDArgs)); 647 } 648 649 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 650 llvm::Metadata *attrMDArgs[] = { 651 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 652 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 653 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 654 Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, attrMDArgs)); 655 } 656 } 657 658 /// Determine whether the function F ends with a return stmt. 659 static bool endsWithReturn(const Decl* F) { 660 const Stmt *Body = nullptr; 661 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 662 Body = FD->getBody(); 663 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 664 Body = OMD->getBody(); 665 666 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 667 auto LastStmt = CS->body_rbegin(); 668 if (LastStmt != CS->body_rend()) 669 return isa<ReturnStmt>(*LastStmt); 670 } 671 return false; 672 } 673 674 void CodeGenFunction::StartFunction(GlobalDecl GD, 675 QualType RetTy, 676 llvm::Function *Fn, 677 const CGFunctionInfo &FnInfo, 678 const FunctionArgList &Args, 679 SourceLocation Loc, 680 SourceLocation StartLoc) { 681 assert(!CurFn && 682 "Do not use a CodeGenFunction object for more than one function"); 683 684 const Decl *D = GD.getDecl(); 685 686 DidCallStackSave = false; 687 CurCodeDecl = D; 688 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 689 if (FD->usesSEHTry()) 690 CurSEHParent = FD; 691 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 692 FnRetTy = RetTy; 693 CurFn = Fn; 694 CurFnInfo = &FnInfo; 695 assert(CurFn->isDeclaration() && "Function already has body?"); 696 697 if (CGM.isInSanitizerBlacklist(Fn, Loc)) 698 SanOpts.clear(); 699 700 if (D) { 701 // Apply the no_sanitize* attributes to SanOpts. 702 for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) 703 SanOpts.Mask &= ~Attr->getMask(); 704 } 705 706 // Apply sanitizer attributes to the function. 707 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 708 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 709 if (SanOpts.has(SanitizerKind::Thread)) 710 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 711 if (SanOpts.has(SanitizerKind::Memory)) 712 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 713 if (SanOpts.has(SanitizerKind::SafeStack)) 714 Fn->addFnAttr(llvm::Attribute::SafeStack); 715 716 // Apply xray attributes to the function (as a string, for now) 717 if (D && ShouldXRayInstrumentFunction()) { 718 if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) { 719 if (XRayAttr->alwaysXRayInstrument()) 720 Fn->addFnAttr("function-instrument", "xray-always"); 721 if (XRayAttr->neverXRayInstrument()) 722 Fn->addFnAttr("function-instrument", "xray-never"); 723 } else { 724 Fn->addFnAttr( 725 "xray-instruction-threshold", 726 llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 727 } 728 } 729 730 // Pass inline keyword to optimizer if it appears explicitly on any 731 // declaration. Also, in the case of -fno-inline attach NoInline 732 // attribute to all functions that are not marked AlwaysInline, or 733 // to all functions that are not marked inline or implicitly inline 734 // in the case of -finline-hint-functions. 735 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 736 const CodeGenOptions& CodeGenOpts = CGM.getCodeGenOpts(); 737 if (!CodeGenOpts.NoInline) { 738 for (auto RI : FD->redecls()) 739 if (RI->isInlineSpecified()) { 740 Fn->addFnAttr(llvm::Attribute::InlineHint); 741 break; 742 } 743 if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyHintInlining && 744 !FD->isInlined() && !Fn->hasFnAttribute(llvm::Attribute::InlineHint)) 745 Fn->addFnAttr(llvm::Attribute::NoInline); 746 } else if (!FD->hasAttr<AlwaysInlineAttr>()) 747 Fn->addFnAttr(llvm::Attribute::NoInline); 748 if (CGM.getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 749 CGM.getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn); 750 } 751 752 // Add no-jump-tables value. 753 Fn->addFnAttr("no-jump-tables", 754 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables)); 755 756 if (getLangOpts().OpenCL) { 757 // Add metadata for a kernel function. 758 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 759 EmitOpenCLKernelMetadata(FD, Fn); 760 } 761 762 // If we are checking function types, emit a function type signature as 763 // prologue data. 764 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 765 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 766 if (llvm::Constant *PrologueSig = 767 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 768 llvm::Constant *FTRTTIConst = 769 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 770 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst }; 771 llvm::Constant *PrologueStructConst = 772 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 773 Fn->setPrologueData(PrologueStructConst); 774 } 775 } 776 } 777 778 // If we're in C++ mode and the function name is "main", it is guaranteed 779 // to be norecurse by the standard (3.6.1.3 "The function main shall not be 780 // used within a program"). 781 if (getLangOpts().CPlusPlus) 782 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 783 if (FD->isMain()) 784 Fn->addFnAttr(llvm::Attribute::NoRecurse); 785 786 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 787 788 // Create a marker to make it easy to insert allocas into the entryblock 789 // later. Don't create this with the builder, because we don't want it 790 // folded. 791 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 792 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 793 794 ReturnBlock = getJumpDestInCurrentScope("return"); 795 796 Builder.SetInsertPoint(EntryBB); 797 798 // Emit subprogram debug descriptor. 799 if (CGDebugInfo *DI = getDebugInfo()) { 800 // Reconstruct the type from the argument list so that implicit parameters, 801 // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 802 // convention. 803 CallingConv CC = CallingConv::CC_C; 804 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) 805 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) 806 CC = SrcFnTy->getCallConv(); 807 SmallVector<QualType, 16> ArgTypes; 808 for (const VarDecl *VD : Args) 809 ArgTypes.push_back(VD->getType()); 810 QualType FnType = getContext().getFunctionType( 811 RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC)); 812 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 813 } 814 815 if (ShouldInstrumentFunction()) 816 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 817 818 // Since emitting the mcount call here impacts optimizations such as function 819 // inlining, we just add an attribute to insert a mcount call in backend. 820 // The attribute "counting-function" is set to mcount function name which is 821 // architecture dependent. 822 if (CGM.getCodeGenOpts().InstrumentForProfiling) 823 Fn->addFnAttr("counting-function", getTarget().getMCountName()); 824 825 if (RetTy->isVoidType()) { 826 // Void type; nothing to return. 827 ReturnValue = Address::invalid(); 828 829 // Count the implicit return. 830 if (!endsWithReturn(D)) 831 ++NumReturnExprs; 832 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 833 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 834 // Indirect aggregate return; emit returned value directly into sret slot. 835 // This reduces code size, and affects correctness in C++. 836 auto AI = CurFn->arg_begin(); 837 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 838 ++AI; 839 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign()); 840 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 841 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 842 // Load the sret pointer from the argument struct and return into that. 843 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 844 llvm::Function::arg_iterator EI = CurFn->arg_end(); 845 --EI; 846 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx); 847 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result"); 848 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy)); 849 } else { 850 ReturnValue = CreateIRTemp(RetTy, "retval"); 851 852 // Tell the epilog emitter to autorelease the result. We do this 853 // now so that various specialized functions can suppress it 854 // during their IR-generation. 855 if (getLangOpts().ObjCAutoRefCount && 856 !CurFnInfo->isReturnsRetained() && 857 RetTy->isObjCRetainableType()) 858 AutoreleaseResult = true; 859 } 860 861 EmitStartEHSpec(CurCodeDecl); 862 863 PrologueCleanupDepth = EHStack.stable_begin(); 864 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 865 866 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 867 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 868 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 869 if (MD->getParent()->isLambda() && 870 MD->getOverloadedOperator() == OO_Call) { 871 // We're in a lambda; figure out the captures. 872 MD->getParent()->getCaptureFields(LambdaCaptureFields, 873 LambdaThisCaptureField); 874 if (LambdaThisCaptureField) { 875 // If the lambda captures the object referred to by '*this' - either by 876 // value or by reference, make sure CXXThisValue points to the correct 877 // object. 878 879 // Get the lvalue for the field (which is a copy of the enclosing object 880 // or contains the address of the enclosing object). 881 LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 882 if (!LambdaThisCaptureField->getType()->isPointerType()) { 883 // If the enclosing object was captured by value, just use its address. 884 CXXThisValue = ThisFieldLValue.getAddress().getPointer(); 885 } else { 886 // Load the lvalue pointed to by the field, since '*this' was captured 887 // by reference. 888 CXXThisValue = 889 EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 890 } 891 } 892 for (auto *FD : MD->getParent()->fields()) { 893 if (FD->hasCapturedVLAType()) { 894 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 895 SourceLocation()).getScalarVal(); 896 auto VAT = FD->getCapturedVLAType(); 897 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 898 } 899 } 900 } else { 901 // Not in a lambda; just use 'this' from the method. 902 // FIXME: Should we generate a new load for each use of 'this'? The 903 // fast register allocator would be happier... 904 CXXThisValue = CXXABIThisValue; 905 } 906 } 907 908 // If any of the arguments have a variably modified type, make sure to 909 // emit the type size. 910 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 911 i != e; ++i) { 912 const VarDecl *VD = *i; 913 914 // Dig out the type as written from ParmVarDecls; it's unclear whether 915 // the standard (C99 6.9.1p10) requires this, but we're following the 916 // precedent set by gcc. 917 QualType Ty; 918 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 919 Ty = PVD->getOriginalType(); 920 else 921 Ty = VD->getType(); 922 923 if (Ty->isVariablyModifiedType()) 924 EmitVariablyModifiedType(Ty); 925 } 926 // Emit a location at the end of the prologue. 927 if (CGDebugInfo *DI = getDebugInfo()) 928 DI->EmitLocation(Builder, StartLoc); 929 } 930 931 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 932 const Stmt *Body) { 933 incrementProfileCounter(Body); 934 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 935 EmitCompoundStmtWithoutScope(*S); 936 else 937 EmitStmt(Body); 938 } 939 940 /// When instrumenting to collect profile data, the counts for some blocks 941 /// such as switch cases need to not include the fall-through counts, so 942 /// emit a branch around the instrumentation code. When not instrumenting, 943 /// this just calls EmitBlock(). 944 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 945 const Stmt *S) { 946 llvm::BasicBlock *SkipCountBB = nullptr; 947 if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 948 // When instrumenting for profiling, the fallthrough to certain 949 // statements needs to skip over the instrumentation code so that we 950 // get an accurate count. 951 SkipCountBB = createBasicBlock("skipcount"); 952 EmitBranch(SkipCountBB); 953 } 954 EmitBlock(BB); 955 uint64_t CurrentCount = getCurrentProfileCount(); 956 incrementProfileCounter(S); 957 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 958 if (SkipCountBB) 959 EmitBlock(SkipCountBB); 960 } 961 962 /// Tries to mark the given function nounwind based on the 963 /// non-existence of any throwing calls within it. We believe this is 964 /// lightweight enough to do at -O0. 965 static void TryMarkNoThrow(llvm::Function *F) { 966 // LLVM treats 'nounwind' on a function as part of the type, so we 967 // can't do this on functions that can be overwritten. 968 if (F->isInterposable()) return; 969 970 for (llvm::BasicBlock &BB : *F) 971 for (llvm::Instruction &I : BB) 972 if (I.mayThrow()) 973 return; 974 975 F->setDoesNotThrow(); 976 } 977 978 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 979 FunctionArgList &Args) { 980 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 981 QualType ResTy = FD->getReturnType(); 982 983 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 984 if (MD && MD->isInstance()) { 985 if (CGM.getCXXABI().HasThisReturn(GD)) 986 ResTy = MD->getThisType(getContext()); 987 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 988 ResTy = CGM.getContext().VoidPtrTy; 989 CGM.getCXXABI().buildThisParam(*this, Args); 990 } 991 992 // The base version of an inheriting constructor whose constructed base is a 993 // virtual base is not passed any arguments (because it doesn't actually call 994 // the inherited constructor). 995 bool PassedParams = true; 996 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 997 if (auto Inherited = CD->getInheritedConstructor()) 998 PassedParams = 999 getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 1000 1001 if (PassedParams) { 1002 for (auto *Param : FD->parameters()) { 1003 Args.push_back(Param); 1004 if (!Param->hasAttr<PassObjectSizeAttr>()) 1005 continue; 1006 1007 IdentifierInfo *NoID = nullptr; 1008 auto *Implicit = ImplicitParamDecl::Create( 1009 getContext(), Param->getDeclContext(), Param->getLocation(), NoID, 1010 getContext().getSizeType()); 1011 SizeArguments[Param] = Implicit; 1012 Args.push_back(Implicit); 1013 } 1014 } 1015 1016 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 1017 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 1018 1019 return ResTy; 1020 } 1021 1022 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1023 const CGFunctionInfo &FnInfo) { 1024 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 1025 CurGD = GD; 1026 1027 FunctionArgList Args; 1028 QualType ResTy = BuildFunctionArgList(GD, Args); 1029 1030 // Check if we should generate debug info for this function. 1031 if (FD->hasAttr<NoDebugAttr>()) 1032 DebugInfo = nullptr; // disable debug info indefinitely for this function 1033 1034 SourceRange BodyRange; 1035 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 1036 CurEHLocation = BodyRange.getEnd(); 1037 1038 // Use the location of the start of the function to determine where 1039 // the function definition is located. By default use the location 1040 // of the declaration as the location for the subprogram. A function 1041 // may lack a declaration in the source code if it is created by code 1042 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 1043 SourceLocation Loc = FD->getLocation(); 1044 1045 // If this is a function specialization then use the pattern body 1046 // as the location for the function. 1047 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 1048 if (SpecDecl->hasBody(SpecDecl)) 1049 Loc = SpecDecl->getLocation(); 1050 1051 // Emit the standard function prologue. 1052 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 1053 1054 // Generate the body of the function. 1055 PGO.assignRegionCounters(GD, CurFn); 1056 if (isa<CXXDestructorDecl>(FD)) 1057 EmitDestructorBody(Args); 1058 else if (isa<CXXConstructorDecl>(FD)) 1059 EmitConstructorBody(Args); 1060 else if (getLangOpts().CUDA && 1061 !getLangOpts().CUDAIsDevice && 1062 FD->hasAttr<CUDAGlobalAttr>()) 1063 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 1064 else if (isa<CXXConversionDecl>(FD) && 1065 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 1066 // The lambda conversion to block pointer is special; the semantics can't be 1067 // expressed in the AST, so IRGen needs to special-case it. 1068 EmitLambdaToBlockPointerBody(Args); 1069 } else if (isa<CXXMethodDecl>(FD) && 1070 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 1071 // The lambda static invoker function is special, because it forwards or 1072 // clones the body of the function call operator (but is actually static). 1073 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 1074 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 1075 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 1076 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 1077 // Implicit copy-assignment gets the same special treatment as implicit 1078 // copy-constructors. 1079 emitImplicitAssignmentOperatorBody(Args); 1080 } else if (Stmt *Body = FD->getBody()) { 1081 EmitFunctionBody(Args, Body); 1082 } else 1083 llvm_unreachable("no definition for emitted function"); 1084 1085 // C++11 [stmt.return]p2: 1086 // Flowing off the end of a function [...] results in undefined behavior in 1087 // a value-returning function. 1088 // C11 6.9.1p12: 1089 // If the '}' that terminates a function is reached, and the value of the 1090 // function call is used by the caller, the behavior is undefined. 1091 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 1092 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 1093 if (SanOpts.has(SanitizerKind::Return)) { 1094 SanitizerScope SanScope(this); 1095 llvm::Value *IsFalse = Builder.getFalse(); 1096 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 1097 "missing_return", EmitCheckSourceLocation(FD->getLocation()), 1098 None); 1099 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1100 EmitTrapCall(llvm::Intrinsic::trap); 1101 } 1102 Builder.CreateUnreachable(); 1103 Builder.ClearInsertionPoint(); 1104 } 1105 1106 // Emit the standard function epilogue. 1107 FinishFunction(BodyRange.getEnd()); 1108 1109 // If we haven't marked the function nothrow through other means, do 1110 // a quick pass now to see if we can. 1111 if (!CurFn->doesNotThrow()) 1112 TryMarkNoThrow(CurFn); 1113 } 1114 1115 /// ContainsLabel - Return true if the statement contains a label in it. If 1116 /// this statement is not executed normally, it not containing a label means 1117 /// that we can just remove the code. 1118 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 1119 // Null statement, not a label! 1120 if (!S) return false; 1121 1122 // If this is a label, we have to emit the code, consider something like: 1123 // if (0) { ... foo: bar(); } goto foo; 1124 // 1125 // TODO: If anyone cared, we could track __label__'s, since we know that you 1126 // can't jump to one from outside their declared region. 1127 if (isa<LabelStmt>(S)) 1128 return true; 1129 1130 // If this is a case/default statement, and we haven't seen a switch, we have 1131 // to emit the code. 1132 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 1133 return true; 1134 1135 // If this is a switch statement, we want to ignore cases below it. 1136 if (isa<SwitchStmt>(S)) 1137 IgnoreCaseStmts = true; 1138 1139 // Scan subexpressions for verboten labels. 1140 for (const Stmt *SubStmt : S->children()) 1141 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 1142 return true; 1143 1144 return false; 1145 } 1146 1147 /// containsBreak - Return true if the statement contains a break out of it. 1148 /// If the statement (recursively) contains a switch or loop with a break 1149 /// inside of it, this is fine. 1150 bool CodeGenFunction::containsBreak(const Stmt *S) { 1151 // Null statement, not a label! 1152 if (!S) return false; 1153 1154 // If this is a switch or loop that defines its own break scope, then we can 1155 // include it and anything inside of it. 1156 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 1157 isa<ForStmt>(S)) 1158 return false; 1159 1160 if (isa<BreakStmt>(S)) 1161 return true; 1162 1163 // Scan subexpressions for verboten breaks. 1164 for (const Stmt *SubStmt : S->children()) 1165 if (containsBreak(SubStmt)) 1166 return true; 1167 1168 return false; 1169 } 1170 1171 1172 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1173 /// to a constant, or if it does but contains a label, return false. If it 1174 /// constant folds return true and set the boolean result in Result. 1175 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1176 bool &ResultBool, 1177 bool AllowLabels) { 1178 llvm::APSInt ResultInt; 1179 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 1180 return false; 1181 1182 ResultBool = ResultInt.getBoolValue(); 1183 return true; 1184 } 1185 1186 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1187 /// to a constant, or if it does but contains a label, return false. If it 1188 /// constant folds return true and set the folded value. 1189 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1190 llvm::APSInt &ResultInt, 1191 bool AllowLabels) { 1192 // FIXME: Rename and handle conversion of other evaluatable things 1193 // to bool. 1194 llvm::APSInt Int; 1195 if (!Cond->EvaluateAsInt(Int, getContext())) 1196 return false; // Not foldable, not integer or not fully evaluatable. 1197 1198 if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 1199 return false; // Contains a label. 1200 1201 ResultInt = Int; 1202 return true; 1203 } 1204 1205 1206 1207 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1208 /// statement) to the specified blocks. Based on the condition, this might try 1209 /// to simplify the codegen of the conditional based on the branch. 1210 /// 1211 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1212 llvm::BasicBlock *TrueBlock, 1213 llvm::BasicBlock *FalseBlock, 1214 uint64_t TrueCount) { 1215 Cond = Cond->IgnoreParens(); 1216 1217 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1218 1219 // Handle X && Y in a condition. 1220 if (CondBOp->getOpcode() == BO_LAnd) { 1221 // If we have "1 && X", simplify the code. "0 && X" would have constant 1222 // folded if the case was simple enough. 1223 bool ConstantBool = false; 1224 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1225 ConstantBool) { 1226 // br(1 && X) -> br(X). 1227 incrementProfileCounter(CondBOp); 1228 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1229 TrueCount); 1230 } 1231 1232 // If we have "X && 1", simplify the code to use an uncond branch. 1233 // "X && 0" would have been constant folded to 0. 1234 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1235 ConstantBool) { 1236 // br(X && 1) -> br(X). 1237 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1238 TrueCount); 1239 } 1240 1241 // Emit the LHS as a conditional. If the LHS conditional is false, we 1242 // want to jump to the FalseBlock. 1243 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1244 // The counter tells us how often we evaluate RHS, and all of TrueCount 1245 // can be propagated to that branch. 1246 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1247 1248 ConditionalEvaluation eval(*this); 1249 { 1250 ApplyDebugLocation DL(*this, Cond); 1251 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1252 EmitBlock(LHSTrue); 1253 } 1254 1255 incrementProfileCounter(CondBOp); 1256 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1257 1258 // Any temporaries created here are conditional. 1259 eval.begin(*this); 1260 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1261 eval.end(*this); 1262 1263 return; 1264 } 1265 1266 if (CondBOp->getOpcode() == BO_LOr) { 1267 // If we have "0 || X", simplify the code. "1 || X" would have constant 1268 // folded if the case was simple enough. 1269 bool ConstantBool = false; 1270 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1271 !ConstantBool) { 1272 // br(0 || X) -> br(X). 1273 incrementProfileCounter(CondBOp); 1274 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1275 TrueCount); 1276 } 1277 1278 // If we have "X || 0", simplify the code to use an uncond branch. 1279 // "X || 1" would have been constant folded to 1. 1280 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1281 !ConstantBool) { 1282 // br(X || 0) -> br(X). 1283 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1284 TrueCount); 1285 } 1286 1287 // Emit the LHS as a conditional. If the LHS conditional is true, we 1288 // want to jump to the TrueBlock. 1289 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1290 // We have the count for entry to the RHS and for the whole expression 1291 // being true, so we can divy up True count between the short circuit and 1292 // the RHS. 1293 uint64_t LHSCount = 1294 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1295 uint64_t RHSCount = TrueCount - LHSCount; 1296 1297 ConditionalEvaluation eval(*this); 1298 { 1299 ApplyDebugLocation DL(*this, Cond); 1300 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1301 EmitBlock(LHSFalse); 1302 } 1303 1304 incrementProfileCounter(CondBOp); 1305 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1306 1307 // Any temporaries created here are conditional. 1308 eval.begin(*this); 1309 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1310 1311 eval.end(*this); 1312 1313 return; 1314 } 1315 } 1316 1317 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1318 // br(!x, t, f) -> br(x, f, t) 1319 if (CondUOp->getOpcode() == UO_LNot) { 1320 // Negate the count. 1321 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1322 // Negate the condition and swap the destination blocks. 1323 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1324 FalseCount); 1325 } 1326 } 1327 1328 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1329 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1330 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1331 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1332 1333 ConditionalEvaluation cond(*this); 1334 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1335 getProfileCount(CondOp)); 1336 1337 // When computing PGO branch weights, we only know the overall count for 1338 // the true block. This code is essentially doing tail duplication of the 1339 // naive code-gen, introducing new edges for which counts are not 1340 // available. Divide the counts proportionally between the LHS and RHS of 1341 // the conditional operator. 1342 uint64_t LHSScaledTrueCount = 0; 1343 if (TrueCount) { 1344 double LHSRatio = 1345 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1346 LHSScaledTrueCount = TrueCount * LHSRatio; 1347 } 1348 1349 cond.begin(*this); 1350 EmitBlock(LHSBlock); 1351 incrementProfileCounter(CondOp); 1352 { 1353 ApplyDebugLocation DL(*this, Cond); 1354 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1355 LHSScaledTrueCount); 1356 } 1357 cond.end(*this); 1358 1359 cond.begin(*this); 1360 EmitBlock(RHSBlock); 1361 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1362 TrueCount - LHSScaledTrueCount); 1363 cond.end(*this); 1364 1365 return; 1366 } 1367 1368 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1369 // Conditional operator handling can give us a throw expression as a 1370 // condition for a case like: 1371 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1372 // Fold this to: 1373 // br(c, throw x, br(y, t, f)) 1374 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1375 return; 1376 } 1377 1378 // If the branch has a condition wrapped by __builtin_unpredictable, 1379 // create metadata that specifies that the branch is unpredictable. 1380 // Don't bother if not optimizing because that metadata would not be used. 1381 llvm::MDNode *Unpredictable = nullptr; 1382 auto *Call = dyn_cast<CallExpr>(Cond); 1383 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1384 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1385 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1386 llvm::MDBuilder MDHelper(getLLVMContext()); 1387 Unpredictable = MDHelper.createUnpredictable(); 1388 } 1389 } 1390 1391 // Create branch weights based on the number of times we get here and the 1392 // number of times the condition should be true. 1393 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1394 llvm::MDNode *Weights = 1395 createProfileWeights(TrueCount, CurrentCount - TrueCount); 1396 1397 // Emit the code with the fully general case. 1398 llvm::Value *CondV; 1399 { 1400 ApplyDebugLocation DL(*this, Cond); 1401 CondV = EvaluateExprAsBool(Cond); 1402 } 1403 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1404 } 1405 1406 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1407 /// specified stmt yet. 1408 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1409 CGM.ErrorUnsupported(S, Type); 1410 } 1411 1412 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1413 /// variable-length array whose elements have a non-zero bit-pattern. 1414 /// 1415 /// \param baseType the inner-most element type of the array 1416 /// \param src - a char* pointing to the bit-pattern for a single 1417 /// base element of the array 1418 /// \param sizeInChars - the total size of the VLA, in chars 1419 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1420 Address dest, Address src, 1421 llvm::Value *sizeInChars) { 1422 CGBuilderTy &Builder = CGF.Builder; 1423 1424 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 1425 llvm::Value *baseSizeInChars 1426 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 1427 1428 Address begin = 1429 Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin"); 1430 llvm::Value *end = 1431 Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end"); 1432 1433 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1434 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1435 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1436 1437 // Make a loop over the VLA. C99 guarantees that the VLA element 1438 // count must be nonzero. 1439 CGF.EmitBlock(loopBB); 1440 1441 llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 1442 cur->addIncoming(begin.getPointer(), originBB); 1443 1444 CharUnits curAlign = 1445 dest.getAlignment().alignmentOfArrayElement(baseSize); 1446 1447 // memcpy the individual element bit-pattern. 1448 Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars, 1449 /*volatile*/ false); 1450 1451 // Go to the next element. 1452 llvm::Value *next = 1453 Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 1454 1455 // Leave if that's the end of the VLA. 1456 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1457 Builder.CreateCondBr(done, contBB, loopBB); 1458 cur->addIncoming(next, loopBB); 1459 1460 CGF.EmitBlock(contBB); 1461 } 1462 1463 void 1464 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 1465 // Ignore empty classes in C++. 1466 if (getLangOpts().CPlusPlus) { 1467 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1468 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1469 return; 1470 } 1471 } 1472 1473 // Cast the dest ptr to the appropriate i8 pointer type. 1474 if (DestPtr.getElementType() != Int8Ty) 1475 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1476 1477 // Get size and alignment info for this aggregate. 1478 CharUnits size = getContext().getTypeSizeInChars(Ty); 1479 1480 llvm::Value *SizeVal; 1481 const VariableArrayType *vla; 1482 1483 // Don't bother emitting a zero-byte memset. 1484 if (size.isZero()) { 1485 // But note that getTypeInfo returns 0 for a VLA. 1486 if (const VariableArrayType *vlaType = 1487 dyn_cast_or_null<VariableArrayType>( 1488 getContext().getAsArrayType(Ty))) { 1489 QualType eltType; 1490 llvm::Value *numElts; 1491 std::tie(numElts, eltType) = getVLASize(vlaType); 1492 1493 SizeVal = numElts; 1494 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 1495 if (!eltSize.isOne()) 1496 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1497 vla = vlaType; 1498 } else { 1499 return; 1500 } 1501 } else { 1502 SizeVal = CGM.getSize(size); 1503 vla = nullptr; 1504 } 1505 1506 // If the type contains a pointer to data member we can't memset it to zero. 1507 // Instead, create a null constant and copy it to the destination. 1508 // TODO: there are other patterns besides zero that we can usefully memset, 1509 // like -1, which happens to be the pattern used by member-pointers. 1510 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1511 // For a VLA, emit a single element, then splat that over the VLA. 1512 if (vla) Ty = getContext().getBaseElementType(vla); 1513 1514 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1515 1516 llvm::GlobalVariable *NullVariable = 1517 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1518 /*isConstant=*/true, 1519 llvm::GlobalVariable::PrivateLinkage, 1520 NullConstant, Twine()); 1521 CharUnits NullAlign = DestPtr.getAlignment(); 1522 NullVariable->setAlignment(NullAlign.getQuantity()); 1523 Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 1524 NullAlign); 1525 1526 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1527 1528 // Get and call the appropriate llvm.memcpy overload. 1529 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 1530 return; 1531 } 1532 1533 // Otherwise, just memset the whole thing to zero. This is legal 1534 // because in LLVM, all default initializers (other than the ones we just 1535 // handled above) are guaranteed to have a bit pattern of all zeros. 1536 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 1537 } 1538 1539 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1540 // Make sure that there is a block for the indirect goto. 1541 if (!IndirectBranch) 1542 GetIndirectGotoBlock(); 1543 1544 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1545 1546 // Make sure the indirect branch includes all of the address-taken blocks. 1547 IndirectBranch->addDestination(BB); 1548 return llvm::BlockAddress::get(CurFn, BB); 1549 } 1550 1551 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1552 // If we already made the indirect branch for indirect goto, return its block. 1553 if (IndirectBranch) return IndirectBranch->getParent(); 1554 1555 CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 1556 1557 // Create the PHI node that indirect gotos will add entries to. 1558 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1559 "indirect.goto.dest"); 1560 1561 // Create the indirect branch instruction. 1562 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1563 return IndirectBranch->getParent(); 1564 } 1565 1566 /// Computes the length of an array in elements, as well as the base 1567 /// element type and a properly-typed first element pointer. 1568 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1569 QualType &baseType, 1570 Address &addr) { 1571 const ArrayType *arrayType = origArrayType; 1572 1573 // If it's a VLA, we have to load the stored size. Note that 1574 // this is the size of the VLA in bytes, not its size in elements. 1575 llvm::Value *numVLAElements = nullptr; 1576 if (isa<VariableArrayType>(arrayType)) { 1577 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 1578 1579 // Walk into all VLAs. This doesn't require changes to addr, 1580 // which has type T* where T is the first non-VLA element type. 1581 do { 1582 QualType elementType = arrayType->getElementType(); 1583 arrayType = getContext().getAsArrayType(elementType); 1584 1585 // If we only have VLA components, 'addr' requires no adjustment. 1586 if (!arrayType) { 1587 baseType = elementType; 1588 return numVLAElements; 1589 } 1590 } while (isa<VariableArrayType>(arrayType)); 1591 1592 // We get out here only if we find a constant array type 1593 // inside the VLA. 1594 } 1595 1596 // We have some number of constant-length arrays, so addr should 1597 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1598 // down to the first element of addr. 1599 SmallVector<llvm::Value*, 8> gepIndices; 1600 1601 // GEP down to the array type. 1602 llvm::ConstantInt *zero = Builder.getInt32(0); 1603 gepIndices.push_back(zero); 1604 1605 uint64_t countFromCLAs = 1; 1606 QualType eltType; 1607 1608 llvm::ArrayType *llvmArrayType = 1609 dyn_cast<llvm::ArrayType>(addr.getElementType()); 1610 while (llvmArrayType) { 1611 assert(isa<ConstantArrayType>(arrayType)); 1612 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1613 == llvmArrayType->getNumElements()); 1614 1615 gepIndices.push_back(zero); 1616 countFromCLAs *= llvmArrayType->getNumElements(); 1617 eltType = arrayType->getElementType(); 1618 1619 llvmArrayType = 1620 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1621 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1622 assert((!llvmArrayType || arrayType) && 1623 "LLVM and Clang types are out-of-synch"); 1624 } 1625 1626 if (arrayType) { 1627 // From this point onwards, the Clang array type has been emitted 1628 // as some other type (probably a packed struct). Compute the array 1629 // size, and just emit the 'begin' expression as a bitcast. 1630 while (arrayType) { 1631 countFromCLAs *= 1632 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1633 eltType = arrayType->getElementType(); 1634 arrayType = getContext().getAsArrayType(eltType); 1635 } 1636 1637 llvm::Type *baseType = ConvertType(eltType); 1638 addr = Builder.CreateElementBitCast(addr, baseType, "array.begin"); 1639 } else { 1640 // Create the actual GEP. 1641 addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(), 1642 gepIndices, "array.begin"), 1643 addr.getAlignment()); 1644 } 1645 1646 baseType = eltType; 1647 1648 llvm::Value *numElements 1649 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1650 1651 // If we had any VLA dimensions, factor them in. 1652 if (numVLAElements) 1653 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1654 1655 return numElements; 1656 } 1657 1658 std::pair<llvm::Value*, QualType> 1659 CodeGenFunction::getVLASize(QualType type) { 1660 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1661 assert(vla && "type was not a variable array type!"); 1662 return getVLASize(vla); 1663 } 1664 1665 std::pair<llvm::Value*, QualType> 1666 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1667 // The number of elements so far; always size_t. 1668 llvm::Value *numElements = nullptr; 1669 1670 QualType elementType; 1671 do { 1672 elementType = type->getElementType(); 1673 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1674 assert(vlaSize && "no size for VLA!"); 1675 assert(vlaSize->getType() == SizeTy); 1676 1677 if (!numElements) { 1678 numElements = vlaSize; 1679 } else { 1680 // It's undefined behavior if this wraps around, so mark it that way. 1681 // FIXME: Teach -fsanitize=undefined to trap this. 1682 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1683 } 1684 } while ((type = getContext().getAsVariableArrayType(elementType))); 1685 1686 return std::pair<llvm::Value*,QualType>(numElements, elementType); 1687 } 1688 1689 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1690 assert(type->isVariablyModifiedType() && 1691 "Must pass variably modified type to EmitVLASizes!"); 1692 1693 EnsureInsertPoint(); 1694 1695 // We're going to walk down into the type and look for VLA 1696 // expressions. 1697 do { 1698 assert(type->isVariablyModifiedType()); 1699 1700 const Type *ty = type.getTypePtr(); 1701 switch (ty->getTypeClass()) { 1702 1703 #define TYPE(Class, Base) 1704 #define ABSTRACT_TYPE(Class, Base) 1705 #define NON_CANONICAL_TYPE(Class, Base) 1706 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1707 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1708 #include "clang/AST/TypeNodes.def" 1709 llvm_unreachable("unexpected dependent type!"); 1710 1711 // These types are never variably-modified. 1712 case Type::Builtin: 1713 case Type::Complex: 1714 case Type::Vector: 1715 case Type::ExtVector: 1716 case Type::Record: 1717 case Type::Enum: 1718 case Type::Elaborated: 1719 case Type::TemplateSpecialization: 1720 case Type::ObjCObject: 1721 case Type::ObjCInterface: 1722 case Type::ObjCObjectPointer: 1723 llvm_unreachable("type class is never variably-modified!"); 1724 1725 case Type::Adjusted: 1726 type = cast<AdjustedType>(ty)->getAdjustedType(); 1727 break; 1728 1729 case Type::Decayed: 1730 type = cast<DecayedType>(ty)->getPointeeType(); 1731 break; 1732 1733 case Type::Pointer: 1734 type = cast<PointerType>(ty)->getPointeeType(); 1735 break; 1736 1737 case Type::BlockPointer: 1738 type = cast<BlockPointerType>(ty)->getPointeeType(); 1739 break; 1740 1741 case Type::LValueReference: 1742 case Type::RValueReference: 1743 type = cast<ReferenceType>(ty)->getPointeeType(); 1744 break; 1745 1746 case Type::MemberPointer: 1747 type = cast<MemberPointerType>(ty)->getPointeeType(); 1748 break; 1749 1750 case Type::ConstantArray: 1751 case Type::IncompleteArray: 1752 // Losing element qualification here is fine. 1753 type = cast<ArrayType>(ty)->getElementType(); 1754 break; 1755 1756 case Type::VariableArray: { 1757 // Losing element qualification here is fine. 1758 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1759 1760 // Unknown size indication requires no size computation. 1761 // Otherwise, evaluate and record it. 1762 if (const Expr *size = vat->getSizeExpr()) { 1763 // It's possible that we might have emitted this already, 1764 // e.g. with a typedef and a pointer to it. 1765 llvm::Value *&entry = VLASizeMap[size]; 1766 if (!entry) { 1767 llvm::Value *Size = EmitScalarExpr(size); 1768 1769 // C11 6.7.6.2p5: 1770 // If the size is an expression that is not an integer constant 1771 // expression [...] each time it is evaluated it shall have a value 1772 // greater than zero. 1773 if (SanOpts.has(SanitizerKind::VLABound) && 1774 size->getType()->isSignedIntegerType()) { 1775 SanitizerScope SanScope(this); 1776 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 1777 llvm::Constant *StaticArgs[] = { 1778 EmitCheckSourceLocation(size->getLocStart()), 1779 EmitCheckTypeDescriptor(size->getType()) 1780 }; 1781 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 1782 SanitizerKind::VLABound), 1783 "vla_bound_not_positive", StaticArgs, Size); 1784 } 1785 1786 // Always zexting here would be wrong if it weren't 1787 // undefined behavior to have a negative bound. 1788 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 1789 } 1790 } 1791 type = vat->getElementType(); 1792 break; 1793 } 1794 1795 case Type::FunctionProto: 1796 case Type::FunctionNoProto: 1797 type = cast<FunctionType>(ty)->getReturnType(); 1798 break; 1799 1800 case Type::Paren: 1801 case Type::TypeOf: 1802 case Type::UnaryTransform: 1803 case Type::Attributed: 1804 case Type::SubstTemplateTypeParm: 1805 case Type::PackExpansion: 1806 // Keep walking after single level desugaring. 1807 type = type.getSingleStepDesugaredType(getContext()); 1808 break; 1809 1810 case Type::Typedef: 1811 case Type::Decltype: 1812 case Type::Auto: 1813 // Stop walking: nothing to do. 1814 return; 1815 1816 case Type::TypeOfExpr: 1817 // Stop walking: emit typeof expression. 1818 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1819 return; 1820 1821 case Type::Atomic: 1822 type = cast<AtomicType>(ty)->getValueType(); 1823 break; 1824 1825 case Type::Pipe: 1826 type = cast<PipeType>(ty)->getElementType(); 1827 break; 1828 } 1829 } while (type->isVariablyModifiedType()); 1830 } 1831 1832 Address CodeGenFunction::EmitVAListRef(const Expr* E) { 1833 if (getContext().getBuiltinVaListType()->isArrayType()) 1834 return EmitPointerWithAlignment(E); 1835 return EmitLValue(E).getAddress(); 1836 } 1837 1838 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 1839 return EmitLValue(E).getAddress(); 1840 } 1841 1842 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1843 llvm::Constant *Init) { 1844 assert (Init && "Invalid DeclRefExpr initializer!"); 1845 if (CGDebugInfo *Dbg = getDebugInfo()) 1846 if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 1847 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1848 } 1849 1850 CodeGenFunction::PeepholeProtection 1851 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1852 // At the moment, the only aggressive peephole we do in IR gen 1853 // is trunc(zext) folding, but if we add more, we can easily 1854 // extend this protection. 1855 1856 if (!rvalue.isScalar()) return PeepholeProtection(); 1857 llvm::Value *value = rvalue.getScalarVal(); 1858 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1859 1860 // Just make an extra bitcast. 1861 assert(HaveInsertPoint()); 1862 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1863 Builder.GetInsertBlock()); 1864 1865 PeepholeProtection protection; 1866 protection.Inst = inst; 1867 return protection; 1868 } 1869 1870 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1871 if (!protection.Inst) return; 1872 1873 // In theory, we could try to duplicate the peepholes now, but whatever. 1874 protection.Inst->eraseFromParent(); 1875 } 1876 1877 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1878 llvm::Value *AnnotatedVal, 1879 StringRef AnnotationStr, 1880 SourceLocation Location) { 1881 llvm::Value *Args[4] = { 1882 AnnotatedVal, 1883 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1884 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1885 CGM.EmitAnnotationLineNo(Location) 1886 }; 1887 return Builder.CreateCall(AnnotationFn, Args); 1888 } 1889 1890 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1891 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1892 // FIXME We create a new bitcast for every annotation because that's what 1893 // llvm-gcc was doing. 1894 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1895 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1896 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1897 I->getAnnotation(), D->getLocation()); 1898 } 1899 1900 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1901 Address Addr) { 1902 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1903 llvm::Value *V = Addr.getPointer(); 1904 llvm::Type *VTy = V->getType(); 1905 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1906 CGM.Int8PtrTy); 1907 1908 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 1909 // FIXME Always emit the cast inst so we can differentiate between 1910 // annotation on the first field of a struct and annotation on the struct 1911 // itself. 1912 if (VTy != CGM.Int8PtrTy) 1913 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1914 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 1915 V = Builder.CreateBitCast(V, VTy); 1916 } 1917 1918 return Address(V, Addr.getAlignment()); 1919 } 1920 1921 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 1922 1923 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 1924 : CGF(CGF) { 1925 assert(!CGF->IsSanitizerScope); 1926 CGF->IsSanitizerScope = true; 1927 } 1928 1929 CodeGenFunction::SanitizerScope::~SanitizerScope() { 1930 CGF->IsSanitizerScope = false; 1931 } 1932 1933 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 1934 const llvm::Twine &Name, 1935 llvm::BasicBlock *BB, 1936 llvm::BasicBlock::iterator InsertPt) const { 1937 LoopStack.InsertHelper(I); 1938 if (IsSanitizerScope) 1939 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 1940 } 1941 1942 void CGBuilderInserter::InsertHelper( 1943 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1944 llvm::BasicBlock::iterator InsertPt) const { 1945 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 1946 if (CGF) 1947 CGF->InsertHelper(I, Name, BB, InsertPt); 1948 } 1949 1950 static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures, 1951 CodeGenModule &CGM, const FunctionDecl *FD, 1952 std::string &FirstMissing) { 1953 // If there aren't any required features listed then go ahead and return. 1954 if (ReqFeatures.empty()) 1955 return false; 1956 1957 // Now build up the set of caller features and verify that all the required 1958 // features are there. 1959 llvm::StringMap<bool> CallerFeatureMap; 1960 CGM.getFunctionFeatureMap(CallerFeatureMap, FD); 1961 1962 // If we have at least one of the features in the feature list return 1963 // true, otherwise return false. 1964 return std::all_of( 1965 ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) { 1966 SmallVector<StringRef, 1> OrFeatures; 1967 Feature.split(OrFeatures, "|"); 1968 return std::any_of(OrFeatures.begin(), OrFeatures.end(), 1969 [&](StringRef Feature) { 1970 if (!CallerFeatureMap.lookup(Feature)) { 1971 FirstMissing = Feature.str(); 1972 return false; 1973 } 1974 return true; 1975 }); 1976 }); 1977 } 1978 1979 // Emits an error if we don't have a valid set of target features for the 1980 // called function. 1981 void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 1982 const FunctionDecl *TargetDecl) { 1983 // Early exit if this is an indirect call. 1984 if (!TargetDecl) 1985 return; 1986 1987 // Get the current enclosing function if it exists. If it doesn't 1988 // we can't check the target features anyhow. 1989 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl); 1990 if (!FD) 1991 return; 1992 1993 // Grab the required features for the call. For a builtin this is listed in 1994 // the td file with the default cpu, for an always_inline function this is any 1995 // listed cpu and any listed features. 1996 unsigned BuiltinID = TargetDecl->getBuiltinID(); 1997 std::string MissingFeature; 1998 if (BuiltinID) { 1999 SmallVector<StringRef, 1> ReqFeatures; 2000 const char *FeatureList = 2001 CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2002 // Return if the builtin doesn't have any required features. 2003 if (!FeatureList || StringRef(FeatureList) == "") 2004 return; 2005 StringRef(FeatureList).split(ReqFeatures, ","); 2006 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2007 CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature) 2008 << TargetDecl->getDeclName() 2009 << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID); 2010 2011 } else if (TargetDecl->hasAttr<TargetAttr>()) { 2012 // Get the required features for the callee. 2013 SmallVector<StringRef, 1> ReqFeatures; 2014 llvm::StringMap<bool> CalleeFeatureMap; 2015 CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2016 for (const auto &F : CalleeFeatureMap) { 2017 // Only positive features are "required". 2018 if (F.getValue()) 2019 ReqFeatures.push_back(F.getKey()); 2020 } 2021 if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature)) 2022 CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature) 2023 << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2024 } 2025 } 2026 2027 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 2028 if (!CGM.getCodeGenOpts().SanitizeStats) 2029 return; 2030 2031 llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 2032 IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 2033 CGM.getSanStats().create(IRB, SSK); 2034 } 2035