1 //===-- BoxedProcedure.cpp ------------------------------------------------===// 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 #include "flang/Optimizer/CodeGen/CodeGen.h" 10 11 #include "flang/Optimizer/Builder/FIRBuilder.h" 12 #include "flang/Optimizer/Builder/LowLevelIntrinsics.h" 13 #include "flang/Optimizer/Dialect/FIRDialect.h" 14 #include "flang/Optimizer/Dialect/FIROps.h" 15 #include "flang/Optimizer/Dialect/FIRType.h" 16 #include "flang/Optimizer/Dialect/Support/FIRContext.h" 17 #include "flang/Optimizer/Support/FatalError.h" 18 #include "flang/Optimizer/Support/InternalNames.h" 19 #include "mlir/IR/PatternMatch.h" 20 #include "mlir/Pass/Pass.h" 21 #include "mlir/Transforms/DialectConversion.h" 22 #include "llvm/ADT/DenseMap.h" 23 24 namespace fir { 25 #define GEN_PASS_DEF_BOXEDPROCEDUREPASS 26 #include "flang/Optimizer/CodeGen/CGPasses.h.inc" 27 } // namespace fir 28 29 #define DEBUG_TYPE "flang-procedure-pointer" 30 31 using namespace fir; 32 33 namespace { 34 /// Options to the procedure pointer pass. 35 struct BoxedProcedureOptions { 36 // Lower the boxproc abstraction to function pointers and thunks where 37 // required. 38 bool useThunks = true; 39 }; 40 41 /// This type converter rewrites all `!fir.boxproc<Func>` types to `Func` types. 42 class BoxprocTypeRewriter : public mlir::TypeConverter { 43 public: 44 using mlir::TypeConverter::convertType; 45 46 /// Does the type \p ty need to be converted? 47 /// Any type that is a `!fir.boxproc` in whole or in part will need to be 48 /// converted to a function type to lower the IR to function pointer form in 49 /// the default implementation performed in this pass. Other implementations 50 /// are possible, so those may convert `!fir.boxproc` to some other type or 51 /// not at all depending on the implementation target's characteristics and 52 /// preference. 53 bool needsConversion(mlir::Type ty) { 54 if (mlir::isa<BoxProcType>(ty)) 55 return true; 56 if (auto funcTy = mlir::dyn_cast<mlir::FunctionType>(ty)) { 57 for (auto t : funcTy.getInputs()) 58 if (needsConversion(t)) 59 return true; 60 for (auto t : funcTy.getResults()) 61 if (needsConversion(t)) 62 return true; 63 return false; 64 } 65 if (auto tupleTy = mlir::dyn_cast<mlir::TupleType>(ty)) { 66 for (auto t : tupleTy.getTypes()) 67 if (needsConversion(t)) 68 return true; 69 return false; 70 } 71 if (auto recTy = mlir::dyn_cast<RecordType>(ty)) { 72 auto visited = visitedTypes.find(ty); 73 if (visited != visitedTypes.end()) 74 return visited->second; 75 [[maybe_unused]] auto newIt = visitedTypes.try_emplace(ty, false); 76 assert(newIt.second && "expected ty to not be in the map"); 77 bool wasAlreadyVisitingRecordType = needConversionIsVisitingRecordType; 78 needConversionIsVisitingRecordType = true; 79 bool result = false; 80 for (auto t : recTy.getTypeList()) { 81 if (needsConversion(t.second)) { 82 result = true; 83 break; 84 } 85 } 86 // Only keep the result cached if the fir.type visited was a "top-level 87 // type". Nested types with a recursive reference to the "top-level type" 88 // may incorrectly have been resolved as not needed conversions because it 89 // had not been determined yet if the "top-level type" needed conversion. 90 // This is not an issue to determine the "top-level type" need of 91 // conversion, but the result should not be kept and later used in other 92 // contexts. 93 needConversionIsVisitingRecordType = wasAlreadyVisitingRecordType; 94 if (needConversionIsVisitingRecordType) 95 visitedTypes.erase(ty); 96 else 97 visitedTypes.find(ty)->second = result; 98 return result; 99 } 100 if (auto boxTy = mlir::dyn_cast<BaseBoxType>(ty)) 101 return needsConversion(boxTy.getEleTy()); 102 if (isa_ref_type(ty)) 103 return needsConversion(unwrapRefType(ty)); 104 if (auto t = mlir::dyn_cast<SequenceType>(ty)) 105 return needsConversion(unwrapSequenceType(ty)); 106 return false; 107 } 108 109 BoxprocTypeRewriter(mlir::Location location) : loc{location} { 110 addConversion([](mlir::Type ty) { return ty; }); 111 addConversion( 112 [&](BoxProcType boxproc) { return convertType(boxproc.getEleTy()); }); 113 addConversion([&](mlir::TupleType tupTy) { 114 llvm::SmallVector<mlir::Type> memTys; 115 for (auto ty : tupTy.getTypes()) 116 memTys.push_back(convertType(ty)); 117 return mlir::TupleType::get(tupTy.getContext(), memTys); 118 }); 119 addConversion([&](mlir::FunctionType funcTy) { 120 llvm::SmallVector<mlir::Type> inTys; 121 llvm::SmallVector<mlir::Type> resTys; 122 for (auto ty : funcTy.getInputs()) 123 inTys.push_back(convertType(ty)); 124 for (auto ty : funcTy.getResults()) 125 resTys.push_back(convertType(ty)); 126 return mlir::FunctionType::get(funcTy.getContext(), inTys, resTys); 127 }); 128 addConversion([&](ReferenceType ty) { 129 return ReferenceType::get(convertType(ty.getEleTy())); 130 }); 131 addConversion([&](PointerType ty) { 132 return PointerType::get(convertType(ty.getEleTy())); 133 }); 134 addConversion( 135 [&](HeapType ty) { return HeapType::get(convertType(ty.getEleTy())); }); 136 addConversion([&](fir::LLVMPointerType ty) { 137 return fir::LLVMPointerType::get(convertType(ty.getEleTy())); 138 }); 139 addConversion( 140 [&](BoxType ty) { return BoxType::get(convertType(ty.getEleTy())); }); 141 addConversion([&](ClassType ty) { 142 return ClassType::get(convertType(ty.getEleTy())); 143 }); 144 addConversion([&](SequenceType ty) { 145 // TODO: add ty.getLayoutMap() as needed. 146 return SequenceType::get(ty.getShape(), convertType(ty.getEleTy())); 147 }); 148 addConversion([&](RecordType ty) -> mlir::Type { 149 if (!needsConversion(ty)) 150 return ty; 151 if (auto converted = convertedTypes.lookup(ty)) 152 return converted; 153 auto rec = RecordType::get(ty.getContext(), 154 ty.getName().str() + boxprocSuffix.str()); 155 if (rec.isFinalized()) 156 return rec; 157 [[maybe_unused]] auto it = convertedTypes.try_emplace(ty, rec); 158 assert(it.second && "expected ty to not be in the map"); 159 std::vector<RecordType::TypePair> ps = ty.getLenParamList(); 160 std::vector<RecordType::TypePair> cs; 161 for (auto t : ty.getTypeList()) { 162 if (needsConversion(t.second)) 163 cs.emplace_back(t.first, convertType(t.second)); 164 else 165 cs.emplace_back(t.first, t.second); 166 } 167 rec.finalize(ps, cs); 168 return rec; 169 }); 170 addArgumentMaterialization(materializeProcedure); 171 addSourceMaterialization(materializeProcedure); 172 addTargetMaterialization(materializeProcedure); 173 } 174 175 static mlir::Value materializeProcedure(mlir::OpBuilder &builder, 176 BoxProcType type, 177 mlir::ValueRange inputs, 178 mlir::Location loc) { 179 assert(inputs.size() == 1); 180 return builder.create<ConvertOp>(loc, unwrapRefType(type.getEleTy()), 181 inputs[0]); 182 } 183 184 void setLocation(mlir::Location location) { loc = location; } 185 186 private: 187 // Maps to deal with recursive derived types (avoid infinite loops). 188 // Caching is also beneficial for apps with big types (dozens of 189 // components and or parent types), so the lifetime of the cache 190 // is the whole pass. 191 llvm::DenseMap<mlir::Type, bool> visitedTypes; 192 bool needConversionIsVisitingRecordType = false; 193 llvm::DenseMap<mlir::Type, mlir::Type> convertedTypes; 194 mlir::Location loc; 195 }; 196 197 /// A `boxproc` is an abstraction for a Fortran procedure reference. Typically, 198 /// Fortran procedures can be referenced directly through a function pointer. 199 /// However, Fortran has one-level dynamic scoping between a host procedure and 200 /// its internal procedures. This allows internal procedures to directly access 201 /// and modify the state of the host procedure's variables. 202 /// 203 /// There are any number of possible implementations possible. 204 /// 205 /// The implementation used here is to convert `boxproc` values to function 206 /// pointers everywhere. If a `boxproc` value includes a frame pointer to the 207 /// host procedure's data, then a thunk will be created at runtime to capture 208 /// the frame pointer during execution. In LLVM IR, the frame pointer is 209 /// designated with the `nest` attribute. The thunk's address will then be used 210 /// as the call target instead of the original function's address directly. 211 class BoxedProcedurePass 212 : public fir::impl::BoxedProcedurePassBase<BoxedProcedurePass> { 213 public: 214 using BoxedProcedurePassBase<BoxedProcedurePass>::BoxedProcedurePassBase; 215 216 inline mlir::ModuleOp getModule() { return getOperation(); } 217 218 void runOnOperation() override final { 219 if (options.useThunks) { 220 auto *context = &getContext(); 221 mlir::IRRewriter rewriter(context); 222 BoxprocTypeRewriter typeConverter(mlir::UnknownLoc::get(context)); 223 mlir::Dialect *firDialect = context->getLoadedDialect("fir"); 224 getModule().walk([&](mlir::Operation *op) { 225 bool opIsValid = true; 226 typeConverter.setLocation(op->getLoc()); 227 if (auto addr = mlir::dyn_cast<BoxAddrOp>(op)) { 228 mlir::Type ty = addr.getVal().getType(); 229 mlir::Type resTy = addr.getResult().getType(); 230 if (llvm::isa<mlir::FunctionType>(ty) || 231 llvm::isa<fir::BoxProcType>(ty)) { 232 // Rewrite all `fir.box_addr` ops on values of type `!fir.boxproc` 233 // or function type to be `fir.convert` ops. 234 rewriter.setInsertionPoint(addr); 235 rewriter.replaceOpWithNewOp<ConvertOp>( 236 addr, typeConverter.convertType(addr.getType()), addr.getVal()); 237 opIsValid = false; 238 } else if (typeConverter.needsConversion(resTy)) { 239 rewriter.startOpModification(op); 240 op->getResult(0).setType(typeConverter.convertType(resTy)); 241 rewriter.finalizeOpModification(op); 242 } 243 } else if (auto func = mlir::dyn_cast<mlir::func::FuncOp>(op)) { 244 mlir::FunctionType ty = func.getFunctionType(); 245 if (typeConverter.needsConversion(ty)) { 246 rewriter.startOpModification(func); 247 auto toTy = 248 mlir::cast<mlir::FunctionType>(typeConverter.convertType(ty)); 249 if (!func.empty()) 250 for (auto e : llvm::enumerate(toTy.getInputs())) { 251 unsigned i = e.index(); 252 auto &block = func.front(); 253 block.insertArgument(i, e.value(), func.getLoc()); 254 block.getArgument(i + 1).replaceAllUsesWith( 255 block.getArgument(i)); 256 block.eraseArgument(i + 1); 257 } 258 func.setType(toTy); 259 rewriter.finalizeOpModification(func); 260 } 261 } else if (auto embox = mlir::dyn_cast<EmboxProcOp>(op)) { 262 // Rewrite all `fir.emboxproc` ops to either `fir.convert` or a thunk 263 // as required. 264 mlir::Type toTy = typeConverter.convertType( 265 mlir::cast<BoxProcType>(embox.getType()).getEleTy()); 266 rewriter.setInsertionPoint(embox); 267 if (embox.getHost()) { 268 // Create the thunk. 269 auto module = embox->getParentOfType<mlir::ModuleOp>(); 270 FirOpBuilder builder(rewriter, module); 271 auto loc = embox.getLoc(); 272 mlir::Type i8Ty = builder.getI8Type(); 273 mlir::Type i8Ptr = builder.getRefType(i8Ty); 274 mlir::Type buffTy = SequenceType::get({32}, i8Ty); 275 auto buffer = builder.create<AllocaOp>(loc, buffTy); 276 mlir::Value closure = 277 builder.createConvert(loc, i8Ptr, embox.getHost()); 278 mlir::Value tramp = builder.createConvert(loc, i8Ptr, buffer); 279 mlir::Value func = 280 builder.createConvert(loc, i8Ptr, embox.getFunc()); 281 builder.create<fir::CallOp>( 282 loc, factory::getLlvmInitTrampoline(builder), 283 llvm::ArrayRef<mlir::Value>{tramp, func, closure}); 284 auto adjustCall = builder.create<fir::CallOp>( 285 loc, factory::getLlvmAdjustTrampoline(builder), 286 llvm::ArrayRef<mlir::Value>{tramp}); 287 rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy, 288 adjustCall.getResult(0)); 289 opIsValid = false; 290 } else { 291 // Just forward the function as a pointer. 292 rewriter.replaceOpWithNewOp<ConvertOp>(embox, toTy, 293 embox.getFunc()); 294 opIsValid = false; 295 } 296 } else if (auto global = mlir::dyn_cast<GlobalOp>(op)) { 297 auto ty = global.getType(); 298 if (typeConverter.needsConversion(ty)) { 299 rewriter.startOpModification(global); 300 auto toTy = typeConverter.convertType(ty); 301 global.setType(toTy); 302 rewriter.finalizeOpModification(global); 303 } 304 } else if (auto mem = mlir::dyn_cast<AllocaOp>(op)) { 305 auto ty = mem.getType(); 306 if (typeConverter.needsConversion(ty)) { 307 rewriter.setInsertionPoint(mem); 308 auto toTy = typeConverter.convertType(unwrapRefType(ty)); 309 bool isPinned = mem.getPinned(); 310 llvm::StringRef uniqName = 311 mem.getUniqName().value_or(llvm::StringRef()); 312 llvm::StringRef bindcName = 313 mem.getBindcName().value_or(llvm::StringRef()); 314 rewriter.replaceOpWithNewOp<AllocaOp>( 315 mem, toTy, uniqName, bindcName, isPinned, mem.getTypeparams(), 316 mem.getShape()); 317 opIsValid = false; 318 } 319 } else if (auto mem = mlir::dyn_cast<AllocMemOp>(op)) { 320 auto ty = mem.getType(); 321 if (typeConverter.needsConversion(ty)) { 322 rewriter.setInsertionPoint(mem); 323 auto toTy = typeConverter.convertType(unwrapRefType(ty)); 324 llvm::StringRef uniqName = 325 mem.getUniqName().value_or(llvm::StringRef()); 326 llvm::StringRef bindcName = 327 mem.getBindcName().value_or(llvm::StringRef()); 328 rewriter.replaceOpWithNewOp<AllocMemOp>( 329 mem, toTy, uniqName, bindcName, mem.getTypeparams(), 330 mem.getShape()); 331 opIsValid = false; 332 } 333 } else if (auto coor = mlir::dyn_cast<CoordinateOp>(op)) { 334 auto ty = coor.getType(); 335 mlir::Type baseTy = coor.getBaseType(); 336 if (typeConverter.needsConversion(ty) || 337 typeConverter.needsConversion(baseTy)) { 338 rewriter.setInsertionPoint(coor); 339 auto toTy = typeConverter.convertType(ty); 340 auto toBaseTy = typeConverter.convertType(baseTy); 341 rewriter.replaceOpWithNewOp<CoordinateOp>(coor, toTy, coor.getRef(), 342 coor.getCoor(), toBaseTy); 343 opIsValid = false; 344 } 345 } else if (auto index = mlir::dyn_cast<FieldIndexOp>(op)) { 346 auto ty = index.getType(); 347 mlir::Type onTy = index.getOnType(); 348 if (typeConverter.needsConversion(ty) || 349 typeConverter.needsConversion(onTy)) { 350 rewriter.setInsertionPoint(index); 351 auto toTy = typeConverter.convertType(ty); 352 auto toOnTy = typeConverter.convertType(onTy); 353 rewriter.replaceOpWithNewOp<FieldIndexOp>( 354 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams()); 355 opIsValid = false; 356 } 357 } else if (auto index = mlir::dyn_cast<LenParamIndexOp>(op)) { 358 auto ty = index.getType(); 359 mlir::Type onTy = index.getOnType(); 360 if (typeConverter.needsConversion(ty) || 361 typeConverter.needsConversion(onTy)) { 362 rewriter.setInsertionPoint(index); 363 auto toTy = typeConverter.convertType(ty); 364 auto toOnTy = typeConverter.convertType(onTy); 365 rewriter.replaceOpWithNewOp<LenParamIndexOp>( 366 index, toTy, index.getFieldId(), toOnTy, index.getTypeparams()); 367 opIsValid = false; 368 } 369 } else if (op->getDialect() == firDialect) { 370 rewriter.startOpModification(op); 371 for (auto i : llvm::enumerate(op->getResultTypes())) 372 if (typeConverter.needsConversion(i.value())) { 373 auto toTy = typeConverter.convertType(i.value()); 374 op->getResult(i.index()).setType(toTy); 375 } 376 rewriter.finalizeOpModification(op); 377 } 378 // Ensure block arguments are updated if needed. 379 if (opIsValid && op->getNumRegions() != 0) { 380 rewriter.startOpModification(op); 381 for (mlir::Region ®ion : op->getRegions()) 382 for (mlir::Block &block : region.getBlocks()) 383 for (mlir::BlockArgument blockArg : block.getArguments()) 384 if (typeConverter.needsConversion(blockArg.getType())) { 385 mlir::Type toTy = 386 typeConverter.convertType(blockArg.getType()); 387 blockArg.setType(toTy); 388 } 389 rewriter.finalizeOpModification(op); 390 } 391 }); 392 } 393 } 394 395 private: 396 BoxedProcedureOptions options; 397 }; 398 } // namespace 399